A dictionary stores key-value pairs: key -> value. Keys must be unique, while values may repeat.
Creating and accessing dictionaries
Dictionaries use {} or dict(). Values are accessed by key, not by numeric index.
info = {"name": "Alice", "age": 24, "height": 179.2}
print(info["name"])
print(info["age"])If a key does not exist, info[key] raises a KeyError. Use get() when the key may be missing.
print(info.get("age"))
print(info.get("score"))KNOWLEDGE QUIZ
Iterating over dictionaries
Iterating over a dictionary directly gives keys.
info = {"name": "Alice", "age": 24, "height": 179.2}
for key in info:
print("key=%s, value=%s" % (key, info[key]))Use items() to get key and value together.
for key, value in info.items():
print("key=%s, value=%s" % (key, value))Dictionary table workbench
Operate by key and watch the table update. Keys are unique; setting an existing key modifies its value.
nameLeafletlanguagePythonlevelbeginnerreturn: —Dictionary methods
Common dictionary methods include:
keys(): get all keys.values(): get all values.items(): get all key-value pairs.update(): update or add pairs.get(): get a value by key.pop(): remove a pair by key.clear(): clear the dictionary.
info = {"name": "Alice"}
print("info =", info)
info.update({"age": 24, "height": 179.2})
print("updated =", info)
print("keys =", info.keys())
print("values =", info.values())
print("age =", info.get("age"))
info.pop("height")
print("after removing height =", info)Word frequency
Dictionaries are excellent counters.
string is a Python standard-library module. We use string.punctuation so strip() can remove punctuation around each word.
import string
text = "Python is simple. Python is powerful."
words = text.split()
frequency = {}
for word in words:
word = word.lower().strip(string.punctuation)
if word not in frequency:
frequency[word] = 1
else:
frequency[word] += 1
for word, count in frequency.items():
print("%s: %d" % (word, count))Output:
python: 2
is: 2
simple: 1
powerful: 1Step-debug a word counter
Run one word at a time. Watch a new key start at 1 and an existing key increment.
01for word in words:02 word = word.lower().strip(...)03 if word not in frequency:04 frequency[word] = 105 else:06 frequency[word] += 1
KNOWLEDGE QUIZ
Solve two-sum with a dictionary
Read integers and a target, then find one pair of indices whose values add to the target using a dictionary.
- Read the integer list and target.
- Store seen values and indices while iterating.
- Print indices as soon as the complement is found.