Python Dictionaries
In this page:
What is a Dictionary?
A dictionary maps unique, immutable keys (strings, numbers, or tuples) to values, and since Python 3.7 insertion order is preserved when you iterate. It's the natural structure for anything you'd otherwise model as a lookup table, like a username-to-user-record mapping.
Example: What is a Dictionary?
user = {"name": "Alex", "age": 30}
print(user)
Accessing and Modifying Values
Reading my_dict[key] raises KeyError if the key is absent, while writing my_dict[key] = value either updates an existing entry or creates a new one -- there's no separate insert operation, assignment handles both cases.
Example: Accessing and Modifying Values
user = {"name": "Alex"}
print(user["name"])
user["name"] = "Sam"
print(user)
Adding and Deleting Items
Assigning to a new key adds it to the dictionary; del my_dict[key] removes an entry and raises KeyError if it's missing, so checking key in my_dict first (or using .pop(key, None)) avoids crashing on absent keys.
Example: Adding and Deleting Items
user = {"name": "Alex"}
user["age"] = 30
del user["age"]
print(user)
Iterating Through a Dictionary
Iterating a dictionary directly (for k in my_dict) yields its keys; .values() yields just the values and .items() yields (key, value) pairs, which is the most common form when you need both during the loop.
Example: Iterating Through a Dictionary
user = {"name": "Alex", "age": 30}
for key, value in user.items():
print(key, value)
Dictionary Length and Duplicate Keys
Dictionary keys are inherently unique -- assigning to an existing key overwrites its value rather than creating a duplicate entry -- and len(my_dict) counts key-value pairs, not individual keys and values separately.
Example: Dictionary Length and Duplicate Keys
user = {"name": "Alex"}
user["name"] = "Sam" # overwrites, not a duplicate
print(user)
print(len(user))
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: