Dictionaries
Dictionaries
Section titled βDictionariesβWhat it means
Section titled βWhat it meansβA dictionary (dict) stores key-value pairs β {"name": "Alice", "age": 30} β and gives you fast, average O(1) lookup by key instead of by numeric position. Keys must be hashable (strings, numbers, tuples of hashable items); values can be anything. Since Python 3.7, dicts preserve insertion order.
Examples
Section titled βExamplesβperson = {"name": "Alice", "age": 30}
person["city"] = "Boston" # add a new keyage = person["age"] # 30 -- KeyError if "age" doesn't existage = person.get("age", 0) # 30 -- safe lookup, returns 0 if missing
for key, value in person.items(): print(key, value)
# dict comprehensionsquares = {n: n * n for n in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}Common mistake
Section titled βCommon mistakeβAccessing a missing key with dict[key] instead of dict.get(key) β this raises KeyError and crashes the program instead of returning a safe default.
person = {"name": "Alice"}
# Crashes if "age" isn't setage = person["age"] # KeyError: 'age'
# Safe -- returns a default instead of crashingage = person.get("age", "unknown") # 'unknown'Quick practice
Section titled βQuick practiceβ-
Whatβs the difference between
d[key]andd.get(key)when the key doesnβt exist?Answer
d[key]raises aKeyError;d.get(key)returnsNone(or a provided default) instead. -
Can a list be used as a dictionary key?
Answer
No β lists are mutable and therefore unhashable. Use a tuple instead if you need a compound, immutable key. -
How do you iterate over both keys and values at once?
Answer
for key, value in my_dict.items():