Skip to content

Dictionaries

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.

person = {"name": "Alice", "age": 30}
person["city"] = "Boston" # add a new key
age = person["age"] # 30 -- KeyError if "age" doesn't exist
age = person.get("age", 0) # 30 -- safe lookup, returns 0 if missing
for key, value in person.items():
print(key, value)
# dict comprehension
squares = {n: n * n for n in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

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 set
age = person["age"] # KeyError: 'age'
# Safe -- returns a default instead of crashing
age = person.get("age", "unknown") # 'unknown'
  1. What’s the difference between d[key] and d.get(key) when the key doesn’t exist?

    Answerd[key] raises a KeyError; d.get(key) returns None (or a provided default) instead.
  2. Can a list be used as a dictionary key?

    AnswerNo β€” lists are mutable and therefore unhashable. Use a tuple instead if you need a compound, immutable key.
  3. How do you iterate over both keys and values at once?

    Answerfor key, value in my_dict.items():