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_personandpersonshould have the same keys and valuescopy_personandpersonshould not be the same object in memory
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules