Python Dictionaries
In this page:
dict_name = {key1: value1, key2: value2}
dict_name[key]
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"]) # raises KeyError if "name" were missing
user["name"] = "Sam" # updates the existing key
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 # adds a new key
del user["age"] # removes it
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(): # yields both key and value together
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))
- Reading a missing key with
d["age"], which raisesKeyError; used.get("age")or check"age" in d. - Using a list as a key, as in
d[[1, 2]] = "x", which raisesTypeErrorbecause keys must be hashable. - Repeating a key in a dictionary literal, as in
{"a": 1, "a": 2}, where the last value silently wins and the first is lost.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: