Editor settings

General settings

Save settings

Learn to program with Python

Looping through dictionary key-value pairs #

The items() method returns a view object that contains the key-value pairs of the dictionary as tuples. By using the for loop and data unpacking, you can iterate over these pairs and access the individual key and value in each iteration.

Here's what happens when we call the method items() on a dictionary.

my_dict = {'name': 'John', 'age': 30, 'country': 'USA'}
print(my_dict.items())
Output:
dict_items([('name', 'John'), ('age', 30), ('country', 'USA')])

We can see that the key-value pairs in the dictionary are now in a list of tuples. We can loop through a dictionary with the items() method like so:

for key, value in my_dict.items():
    print(key, value)
Output
name John
age 30
country USA

Exercise #

Make a copy copy_person from the dictionary person.

Tests #

  • copy_person and person should have the same keys and values
  • copy_person and person should not be the same object in memory
Output will be displayed here