Iterating over dictionaries

Published

2023-07-31

Iterating over dictionaries

If we iterate over a dictionary as we do with a list, this yields the dictionary’s keys.

>>> furniture = {'living room': ['armchair', 'sofa', 'table'],
...              'bedroom': ['bed', 'nightstand', 'dresser'],
...              'office': ['desk', 'chair', 'cabinet']}
...
>>> for x in furniture:
...     print(x)
... 
living room
bedroom
office

Usually, when iterating over a dictionary we use dictionary view objects. These objects provide a dynamic view into a dictionary’s keys, values, or entries.

Dictionaries have three different view objects: items, keys, and values. Dictionaries have methods that return these view objects:

  • dict.keys() which provides a view of a dictionary’s keys,
  • dict.values() which provides a view of a dictionary’s values, and
  • dict.items() which provides tuples of key/value pairs.

Dictionary view objects are all iterable.

Iterating over the keys of a dictionary

>>> furniture = {'living room': ['armchair', 'sofa', 'table'],
...              'bedroom': ['bed', 'nightstand', 'dresser'],
...              'office': ['desk', 'chair', 'cabinet']}
>>> for key in furniture.keys():
...     print(key)
... 
living room
bedroom
office

Note that it’s common to exclude .keys() if it’s keys you want, since the default behavior is to iterate over keys (as shown in the previous example).

Iterating over the values of a dictionary

>>> for value in furniture.values():
...     print(value)
... 
['armchair', 'sofa', 'table']
['bed', 'nightstand', 'dresser']
['desk', 'chair', 'cabinet']

Iterating over the items of a dictionary

>>> for item in furniture.items():
...     print(item)
... 
('living room', ['armchair', 'sofa', 'table'])
('bedroom', ['bed', 'nightstand', 'dresser'])
('office', ['desk', 'chair', 'cabinet'])

Iterating over the items of a dictionary using tuple unpacking

>>> for key, value in furniture.items():
...     print(f"Key: '{key}', value: {value}")
... 
Key: 'living room', value: ['armchair', 'sofa', 'table']
Key: 'bedroom', value: ['bed', 'nightstand', 'dresser']
Key: 'office', value: ['desk', 'chair', 'cabinet']

Some examples

Let’s say we wanted to count the number of pieces of furniture in our dwelling.

>>> count = 0
>>> for lst in furniture.values():
...     count = count + len(lst)
...
>>> count
9

Let’s say we wanted to find all the students in the class who are not CS majors, assuming the items in our dictionary look like this:

>>> students = 
...    {'esmerelda' : {'class': 2024, 'major': 'ENSC', 'gpa': 3.08},
...     'winston': {'class': 2023, 'major': 'CS', 'gpa': 3.30},
...     'clark': {'class': 2022, 'major': 'PHYS', 'gpa': 2.95},
...     'kumiko': {'class': 2023, 'major': 'CS', 'gpa': 3.29},
...     'abeba' : {'class': 2024, 'major': 'MATH', 'gpa': 3.71}}

One approach:

>>> non_cs_majors = []
>>> for student, info in students.items():
...    if info['major'] != 'CS':
...        non_cs_majors.append(student)
...
>>> non_cs_majors
['esmerelda', 'clark', 'abeba']

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).