Dictionary Methods

Each dictionary come equipped with methods that can be used to access its keys, its values, or both. We will now explore each of the following methods:

  • The keys() method of a dictionary returns a collection of the keys for items that dictionary.

  • The values() method of a dictionary returns a collection of the values for items in that dictionary.

  • The items() method of a dictionary returns a collection of the key/value tuples for items in that dictionary.

We will illustrate the use of these methods in the cell below.

Dictionary elements are not ordered, and so dictionaries don’t allow for slicing. You can, however, loop over the elements of a dictionary.

print(salary_dict.keys())
print(salary_dict.values())
print(salary_dict.items())
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-1d43d7a847a9> in <module>
----> 1 print(salary_dict.keys())
      2 print(salary_dict.values())
      3 print(salary_dict.items())

NameError: name 'salary_dict' is not defined

The objects returned by the keys(), values(), and items() methods are not lists. Each method instead returns an object with a type specific to that function (dict_keys, dict_values, and dict_items). We can convert these objects to list using the list() function, if necessary. We can also use a for loop to iterate over these objects without first converting them to lists.

In the cell below, the values() in a loop to display the values stored in our dictionary.

for v in salary_dict.values():
    print(v)
43700
50250
39800

The values() method gives us no way of accessing the keys associated with individual values. If we want to display both keys and values, we can use keys() in a loop to iterate over the keys, displaying each key along with the value associated with it. We display the results using an f-string.

for k in salary_dict.keys():
    print(f'{k}: {salary_dict[k]}')
Anna: 43700
Beth: 50250
Drew: 39800

We can obtain the same results as above by instead using the items() method. When iterate over the dictionary items, we are provided a tuple of key values pairs at each step. We can unpack this tuple into separate variables. This saves us from having to use the keys to look up the associated values.

for k, v in salary_dict.items():
    print(f'{k}: {v}')
Anna: 43700
Beth: 50250
Drew: 39800