Python Dictionary (dict): Keys and Values
A dictionary (dict) is a data type that finds values by key instead of by index. You store pairs in the form {key: value} and read and write with d[key]. Looking up, adding and changing are fast no matter how many keys there are.
d = {key: value, key: value}
d[key] # read
d[key] = value # add or change
Create, read and change
d[key] = value adds the key if it isn't there and replaces the value if it is. The same key can appear only once. To remove one, use del.
ages = {"kim": 12, "lee": 15}print(ages["kim"])ages["park"] = 9ages["kim"] += 1del ages["lee"]print(ages)print(len(ages))12
{'kim': 13, 'park': 9}
2
Handling missing keys: in and get
Reading a missing key with d[key] raises an error. Ask first with in whether the key is there, or use get, which lets you choose the value to use when it is missing.
stock = {"apple": 3, "kiwi": 0}print("apple" in stock, "plum" in stock)print(stock.get("apple", 0))print(stock.get("plum", 0))print(stock.get("plum"))print(3 in stock)True False 3 0 None False
Without a second argument, get returns None when the key is missing. in looks at keys only. Even though the value 3 is stored, 3 in stock is false.
Looping over keys and values together
A plain for over a dictionary gives you the keys. Use items() to get the key and the value together, or values() when you need only the values. The order is the order they were added (since Python 3.7).
price = {"tea": 3, "milk": 2, "juice": 4}for name in price: print(name, price[name])for name, p in price.items(): print(f"{name}={p}", end=" ")print()print(sum(price.values()))print(list(price))tea 3 milk 2 juice 4 tea=3 milk=2 juice=4 9 ['tea', 'milk', 'juice']
Counting
This is the most common use. For a key you haven't seen yet, get(key, 0) gives 0, so one line adds 1 whether the key is there or not.
words = "to be or not to be".split()counts = {}for w in words: counts[w] = counts.get(w, 0) + 1print(counts)print(counts["be"], len(counts)){'to': 2, 'be': 2, 'or': 1, 'not': 1}
2 4
Printing in key order or value order
sorted(d) gives a sorted list of the keys. To see the largest values first, sort items() by value.
counts = {"to": 2, "be": 2, "or": 1, "not": 1}for w in sorted(counts): print(w, counts[w])top = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))print(top[:2])be 2
not 1
or 1
to 2
[('be', 2), ('to', 2)]
Common mistakes
Reading a missing key with []
ages = {"kim": 12}
print(ages["park"])
→ KeyError: 'park'
Choose a value for the missing case, as in ages.get("park", 0), or check first with if "park" in ages:. A key that differs in upper or lower case, or in spaces before or after it, is a missing key too.
Deleting keys while looping
d = {"a": 1, "b": 0, "c": 0}
for k in d:
if d[k] == 0:
del d[k]
→ RuntimeError: dictionary changed size during iteration
Copy the keys into a list first and loop over that: for k in list(d):. Or build a new dictionary with only what you want to keep: d = {k: v for k, v in d.items() if v != 0}.
Using a list as a key
seen = {}
seen[[1, 2]] = True
→ TypeError: unhashable type: 'list'
A key has to be a value that does not change. Strings, numbers and tuples work; lists and dictionaries don't. To use two values as a key, such as coordinates, use a tuple: seen[(1, 2)] = True.
Thinking {} is an empty set
a = {}
b = set()
print(type(a).__name__, type(b).__name__)
→ {} is an empty dictionary
Make an empty set with set(). Braces make a set only when there are values inside, as in {1, 2}.