Python Dictionaries
A dictionary (dict) stores data as key–value pairs. Instead of looking items up by position like a list, you look them up by a meaningful key: a word gives its definition, a username gives a profile, a product code gives a price.
capitals = {
"Vietnam": "Hanoi",
"Japan": "Tokyo",
"France": "Paris",
}
print(capitals["Japan"])
print(len(capitals))
print(capitals)Tokyo
3
{'Vietnam': 'Hanoi', 'Japan': 'Tokyo', 'France': 'Paris'}
Key properties
| Property | Meaning |
|---|---|
| Keys are unique | Assigning to an existing key replaces its value |
| Keys must be hashable | Strings, numbers and tuples work; lists don't |
| Values can be anything | Including lists and other dicts |
| Insertion-ordered | Since Python 3.7, items stay in the order they were added |
| Mutable | Add, change and remove pairs freely |
Reading values safely
Using d[key] with a missing key raises KeyError. get() returns None — or a default you choose — instead:
stock = {"apple": 12, "pear": 0}
print(stock.get("apple"))
print(stock.get("mango"))
print(stock.get("mango", 0))
print("pear" in stock) # membership tests the keys
try:
print(stock["mango"])
except KeyError as err:
print("Missing key:", err)12
None
0
True
Missing key: 'mango'
Adding, changing and removing
user = {"name": "Thu", "age": 24}
user["age"] = 25 # change
user["city"] = "Can Tho" # add
user.update({"age": 26, "role": "admin"})
print(user)
removed = user.pop("role") # remove and return the value
print(removed)
del user["city"]
print(user)
print(user.setdefault("country", "VN")) # add only if missing
print(user){'name': 'Thu', 'age': 26, 'city': 'Can Tho', 'role': 'admin'}
admin
{'name': 'Thu', 'age': 26}
VN
{'name': 'Thu', 'age': 26, 'country': 'VN'}
Looping over a dictionary
prices = {"coffee": 3.0, "tea": 2.5, "juice": 4.0}
for item in prices: # keys
print(item)
for item, price in prices.items(): # key and value together
print(f"{item:<7}{price:>5.2f}")
print(list(prices.keys()))
print(list(prices.values()))
print(sum(prices.values()))coffee
tea
juice
coffee 3.00
tea 2.50
juice 4.00
['coffee', 'tea', 'juice']
[3.0, 2.5, 4.0]
9.5
Useful methods
| Method | Returns / does |
|---|---|
get(k, default) |
Value for k, or default |
keys(), values(), items() |
Live views of the keys, values, pairs |
update(other) |
Merge another dict into this one |
pop(k) |
Remove k and return its value |
setdefault(k, v) |
Return value of k, inserting v first if missing |
copy() |
Shallow copy |
clear() |
Remove everything |
Python 3.9 also added the merge operators a | b (new dict) and a |= b (update in place).
Counting with a dictionary
Counting how often things occur is a classic dictionary job:
text = "the quick brown fox jumps over the lazy dog the end"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts["the"])
top = sorted(counts.items(), key=lambda kv: kv[1], reverse=True)[:2]
print(top)3
[('the', 3), ('quick', 1)]
Tip: The standard library's
collections.Counterdoes this in one line:Counter(text.split()).most_common(2).
Nested dictionaries
Values can be dictionaries themselves, which is how JSON data from web APIs usually looks:
team = {
"lead": {"name": "Hai", "langs": ["Python", "Go"]},
"dev": {"name": "Nga", "langs": ["Python"]},
}
print(team["lead"]["name"])
print(team["dev"]["langs"][0])
for role, info in team.items():
print(role, "->", ", ".join(info["langs"]))Hai
Python
lead -> Python, Go
dev -> Python
Test yourself
What does d.get("x", 0) return if "x" is not a key of d?
- None
- 0
- KeyError
- "x"
Which method gives you key-value pairs to loop over?
- keys()
- values()
- items()
- pairs()
Which of these can NOT be a dictionary key?
- "name"
- 42
- (1, 2)
- [1, 2]