Python Dictionaries: Keys, Values and Loops
Look up a value by its name instead of its position. Create, update and loop over key-value pairs.
- Creating dictionaries and reading values
- Adding, updating and deleting keys
- Looping with .items() and using .get()
"name""Ada""score"92"course""Python"Keys point to values
The problem
Data often comes as labeled facts: a student's name, score and course; a product's price and stock. Keeping them in a list means remembering that position 1 is the score. Finding one item in a long list also means searching every entry.
Think of it like this
A dictionary is like a student record card with labeled lines: name, score, course. Each label (the key) appears once, and next to it is what was written (the value). To find the score you go straight to the line labeled score, without reading the whole card. Writing on a label that already exists replaces what was there.
"name": "Ada"🏷️ One line on the card: the label name, with Ada written next to itstudent["course"] = "Python"➕ Write a new labeled line (or replace one)student.items()📜 Read the card line by line: each label and what is writtenstudent["score"]🔎 Go straight to the line labeled scoreA dictionary (dict) stores key-value pairs; each key is unique and gives fast access to its value.
Key points
student = {"name": "Ada", "score": 92}maps each key to a value.student["course"] = "Python"adds a new key; assigning to an existing key replaces its value.student.items()gives each key and value together, which the loop unpacks intokeyandvalue.- Dictionaries keep the order in which keys were added, so
courseis printed last.
When should you use it?
- Records with named fields: a user, a product, a configuration.
- Fast lookups by ID or name, such as a username to a profile.
- Counting things, with the item as the key and the count as the value.
When not to use it
- A simple ordered sequence with no names, such as a list of scores: use a list.
- Many records with the same fields and behavior: a class gives them a clear structure.
See how it works
Type a key and store or look it up. Python hashes the key to find its slot directly, without searching through every entry.
Example code
student = {"name": "Ada", "score": 92}
student["course"] = "Python"
for key, value in student.items():
print(f"{key}: {value}")
Result of running the code
name: Ada
score: 92
course: Python
Code explanation
Square brackets add or update a value. The items method returns each key and value for iteration.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the input and predict the output before running.
- Handle empty or invalid input.
- Wrap the logic in a function and add more test cases.
Python dictionary methods and operations
ages = {"Ada": 36, "Lin": 29} | Create a dictionary |
ages["Ada"] | Get a value (KeyError if the key is missing) |
ages.get("Sam", 0) | Get a value, or a default if the key is missing |
ages["Sam"] = 41 | Add a key, or update it if it exists |
del ages["Lin"] | Remove a key |
ages.pop("Sam", None) | Remove a key and return its value, without an error if it is missing |
"Ada" in ages | True if the key exists |
ages.keys(), ages.values(), ages.items() | Views of the keys, the values and the key-value pairs |
for name, age in ages.items(): | Loop over keys and values together |
ages.update(more), ages | more | Merge another dictionary (the | operator needs Python 3.9+) |
len(ages) | Number of keys |
Common mistakes with Python dictionaries
Reading a key that does not exist
Square brackets raise KeyError for a missing key. Use get() with a default, or check with in first.
ages = {"Ada": 36}
print(ages["Sam"]) # KeyError: 'Sam'
ages = {"Ada": 36}
print(ages.get("Sam", "unknown")) # unknown
Deleting keys while looping over the dictionary
Changing the size of a dictionary during a loop raises RuntimeError. Loop over a copy of the keys instead.
stock = {"apple": 0, "pear": 3}
for name in stock:
if stock[name] == 0:
del stock[name] # RuntimeError
stock = {"apple": 0, "pear": 3}
for name in list(stock):
if stock[name] == 0:
del stock[name]
print(stock) # {'pear': 3}
Using a list as a key
Keys must be hashable, so lists cannot be keys. Use a tuple instead.
points = {[0, 0]: "origin"} # TypeError: unhashable type: 'list'
points = {(0, 0): "origin"}
print(points[(0, 0)]) # origin
Expecting in to search the values
in checks the keys of a dictionary, not its values.
ages = {"Ada": 36}
print(36 in ages) # False
ages = {"Ada": 36}
print(36 in ages.values()) # True
Frequently asked questions
How do I loop through a dictionary in Python?
Loop over ages.items() to get each key and value together: for name, age in ages.items(). Looping over the dictionary itself gives only the keys.
How do I check if a key exists in a dictionary?
Use the in operator: if "Ada" in ages. To read a value that may be missing, use ages.get("Ada") or ages.get("Ada", default) instead.
Are Python dictionaries ordered?
Yes. Since Python 3.7, dictionaries keep the order in which keys were inserted, and loops return them in that order.
How do I merge two dictionaries?
Use a | b in Python 3.9 and later to get a new dictionary, a.update(b) to change a in place, or {**a, **b} in older versions. When a key exists in both, the value from b wins.
When should I use a dictionary instead of a list?
Use a dictionary when you look items up by a name or ID, such as a user name or product code. Use a list when the order matters and you look items up by position.
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Character Frequency Count how often each character appears. Easy
- First Unique Character Find the first character that appears only once. Easy
- Tournament Standings Rank teams from match records. Medium