Hey everyone,
I’m currently learning Python and working with dictionaries. I know how to create one, but now I need to iterate through a dictionary in Python to access both the keys and the values.
What’s the proper way to do this? Should I loop over the keys, values, or both? And what if I want to update values as I go? Would appreciate examples and best practices!
Thanks in advance.
Great question and one every Python developer asks at some point! Whether you’re processing image metadata, user preferences, or API responses, you’ll often need to iterate through a dictionary in Python.
Let’s break down all the different ways you can do it and when to use each.
A dictionary in Python is a collection of key-value pairs, like so:
image = {
"filename": "sunset.jpg",
"width": 1920,
"height": 1080,
"format": "JPEG"
}
Code language: JavaScript (javascript)
You can access values with image["width"]
, but when you want to process all the entries, like exporting or modifying data, you’ll need to iterate.
This is the most basic loop:
for key in image:
print(key)
Code language: PHP (php)
Or:
for key in image.keys():
print(key)
Code language: CSS (css)
Use this when you only need the keys and don’t care about the values.
for value in image.values():
print(value)
Code language: CSS (css)
Use this when you only care about the data, not the names of the fields.
This is the most useful and common way:
for key, value in image.items():
print(f"{key}: {value}")
Code language: PHP (php)
dict.items()
gives you both key and value at the same time.
Let’s say you’re storing metadata for a set of images:
photos = {
"sunset.jpg": {"width": 1920, "height": 1080, "format": "JPEG"},
"forest.png": {"width": 1280, "height": 720, "format": "PNG"},
"portrait.webp": {"width": 600, "height": 900, "format": "WEBP"},
}
for filename, details in photos.items():
print(f"File: {filename}")
for key, value in details.items():
print(f" {key}: {value}")
# Output:
File: sunset.jpg
width: 1920
height: 1080
format: JPEG
...
Code language: PHP (php)
You’re now looping through nested dictionaries!
Let’s say you want to resize every image by half:
for photo in photos.values():
photo["width"] //= 2
photo["height"] //= 2
Code language: JavaScript (javascript)
This works because you’re modifying the original dictionary’s values directly.
Don’t modify the dictionary keys or structure while looping over it:
# This is risky!
for key in photos:
if photos[key]["width"] < 1000:
del photos[key] # This can cause a runtime error
Code language: CSS (css)
Instead, build a new dictionary or collect keys to delete after the loop.
Say you want to get all images in PNG format:
png_photos = {
name: data for name, data in photos.items() if data["format"] == "PNG"
}
Code language: JavaScript (javascript)
This is called a dictionary comprehension, just like list comprehensions, but for dicts.
Syntax | Use Case |
for key in dict | Just need the keys |
for value in dict.values() | Just need the values |
for key, value in dict.items() | Best for accessing both |
Dictionary Comprehensions | Filter or modify into a new dict |
Want to loop through a dictionary in sorted order?
for key in sorted(image.keys()):
print(f"{key}: {image[key]}")
Code language: PHP (php)
Or sort by values:
for key, value in sorted(image.items(), key=lambda item: item[1]):
print(f"{key}: {value}")
Code language: PHP (php)
Perfect for displaying clean UI data or reports.
Q: Can I change the dictionary while iterating?
A: Not safely. If you need to change its structure (add/remove keys), do it after or use a copy.
Q: How do I iterate through a nested dictionary?
A: Use a nested loop like shown above, or recursively loop if you don’t know the depth.
Q: Can I use enumerate()
with a dictionary?
A: You can, but it gives you an index and the key, not usually needed with dictionaries.
for i, key in enumerate(image):
print(i, key, image[key])
Code language: CSS (css)
Use .items()
to get both key and value:
for k, v in my_dict.items():
print(k, v)
Code language: CSS (css)
- Use
.values()
if you only care about the values. - Use
.keys()
(or justfor k in dict
) if you only need keys. - Use dictionary comprehensions to filter or transform data efficiently.
Knowing how to iterate through a dictionary in Python unlocks everything from JSON parsing to database formatting to real-time data pipelines. Whether you’re analyzing image metadata, building a config loader, or debugging API responses, this is one of those tools you’ll use daily.