0
0
Pythonprogramming~5 mins

Dictionary iteration in Python

Choose your learning style9 modes available
Introduction

Dictionary iteration helps you look at each item in a dictionary one by one. This lets you use or change the data inside easily.

You want to print all names and phone numbers stored in a phone book dictionary.
You need to check each product and its price in a shopping list dictionary.
You want to find all keys or values that meet a certain condition in a dictionary.
You want to update or change values for each key in a dictionary.
Syntax
Python
for key in dictionary:
    # use key or dictionary[key]

for key, value in dictionary.items():
    # use key and value

You can loop over just keys or both keys and values.

Use .items() to get both key and value together.

Examples
This prints all keys in the dictionary.
Python
my_dict = {'apple': 3, 'banana': 5}
for key in my_dict:
    print(key)
This prints each key with its value.
Python
my_dict = {'apple': 3, 'banana': 5}
for key, value in my_dict.items():
    print(f"{key} -> {value}")
This prints all values only.
Python
my_dict = {'apple': 3, 'banana': 5}
for value in my_dict.values():
    print(value)
Sample Program

This program shows how to loop over just keys and then over both keys and values in a dictionary.

Python
fruits = {'apple': 2, 'banana': 4, 'cherry': 6}

print('Keys:')
for fruit in fruits:
    print(fruit)

print('\nKeys and values:')
for fruit, count in fruits.items():
    print(f'{fruit} -> {count}')
OutputSuccess
Important Notes

Using .items() is the most common way to get both keys and values.

Looping over a dictionary without .items() gives you keys only.

Summary

Dictionary iteration lets you visit each key or each key-value pair.

Use for key in dict to get keys.

Use for key, value in dict.items() to get keys and values.