Dictionary Functions¶
Earlier, we used dictionary method items
to iterate through a dictionary’s key–value pairs. Similarly, built-in functions keys
and values
can be used to iterate through only a dictionary’s keys or values, respectively:
months = {'January': 1, 'February': 2, 'March': 3}
for month_name in months.keys():
print(month_name)
for month_num in months.values():
print(month_num)
Dictionary functions items
, keys
and values
each return a view of a dictionary’s data. When you iterate over a view, it “sees” the dictionary’s current contents—it does not have its own copy of the data.
To show that views do not maintain their own copies of a dictionary’s data, let’s first save the view returned by keys
into the variable months_view
, then loop through it:
months = {'January': 1, 'February': 2, 'March': 3}
month_views = months.keys()
for key in month_views:
print(key)
Next, let’s add a new key–value pair to months and display the updated dictionary:
months['December'] = 12
Now, let’s loop through months_view
again. The key we added above will be displayed:
for key in month_views:
print(key) # December will now be displayed
Do not modify a dictionary while iterating through a view. According to the Python Standard Library documentation, either you’ll get a RuntimeError or the loop might not process all of the view’s values.
Converting Dictionaries to Lists:
You might occasionally need lists of a dictionary’s keys, values or key–value pairs. To obtain such a list, pass the view returned by keys, values or items to the built-in `list` function. Modifying these lists does not modify the corresponding dictionary:listOfKeys = list(months.keys())
listOfValues = list(months.values())
listOfKeysValues = list(months.items())
Updating Dictionaries:
You may insert and update key–value pairs using dictionary function `update`. First, let’s create an empty country_codes dictionary:country_codes = {}
The following update call receives a dictionary of key–value pairs to insert or update:
country_codes.update({'South Africa': 'za'})