4.5 Dictionaries
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.
python
info = {"name": "Alice", "age": 24, "height": 179.2}
print(info["name"]) # Alice
print(info["age"]) # 24If a key does not exist, info[key] raises a KeyError. Use get() when the key may be missing.
python
print(info.get("age")) # 24
print(info.get("score")) # NoneLoading concept check...
Iterating over dictionaries
Iterating over a dictionary directly gives keys.
python
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.
python
for key, value in info.items():
print("key=%s, value=%s" % (key, value))Loading interactive lab...
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.
python
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.
Note
string is a Python standard-library module. We use it here for string.punctuation, a ready-made string of common punctuation marks, so strip() can remove punctuation around each word.python
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:
text
python: 2
is: 2
simple: 1
powerful: 1Loading concept check...
Loading practice...