Iterating over Dictionaries#

Dictionaries in Python provide several ways to iterate over their contents.

Looping Over Keys#

The simplest way to iterate over a dictionary is to loop over its keys:

element_data = {'H': 1, 'He': 2, 'Li': 3, 'Be': 4}

for element in element_data:
    print(element)
H
He
Li
Be

This method gives you access to the keys, but not directly to the values.

Looping over Key–Value Pairs#

To access both keys and values during iteration, use the items() method:

for key_value_pair in element_data.items():
    print(key_value_pair)
('H', 1)
('He', 2)
('Li', 3)
('Be', 4)

We can also use unpacking to assign the keys and values to separate variables. (This is equivalent to looping over two lists in parallel).

for element, atomic_number in element_data.items():
    print(f'{element}: {atomic_number}')
H: 1
He: 2
Li: 3
Be: 4

Looping over Values#

If you only need the values, use the values() method:

for atomic_number in element_data.values():
    print(atomic_number)
1
2
3
4

Enumerating Items#

Somethimes, you might need an index along with key-value pairs. You can combine enumerate() with items():

for index, (element, atomic_number) in enumerate(element_data.items()):
    print(f"{index}: {element} - {atomic_number}")
0: H - 1
1: He - 2
2: Li - 3
3: Be - 4

Example: Chemical Element Properties#

This example uses a more complex dictionary, where each value is itself a dictionary of element properties.

elements = {
    'H': {'name': 'Hydrogen', 'atomic_number': 1, 'period': 1, 'group': 1},
    'He': {'name': 'Helium', 'atomic_number': 2, 'period': 1, 'group': 18},
    'Li': {'name': 'Lithium', 'atomic_number': 3, 'period': 2, 'group': 1},
    'Be': {'name': 'Beryllium', 'atomic_number': 4, 'period': 2, 'group': 2}
}

# Printing all element names and their periods
for symbol, properties in elements.items():
    print(f"{properties['name']} (Symbol: {symbol}) is in period {properties['period']}")

# Finding elements in the first group
group_1_elements = [properties['name'] for symbol, properties in elements.items() if properties['group'] == 1]
print("Elements in group 1:", group_1_elements)
Hydrogen (Symbol: H) is in period 1
Helium (Symbol: He) is in period 1
Lithium (Symbol: Li) is in period 2
Beryllium (Symbol: Be) is in period 2
Elements in group 1: ['Hydrogen', 'Lithium']