Dictionary methods
All Python types, including dictionaries, have their own methods. Since dictionaries include keys and values, it’s common to access them using dictionary methods. In the following exercise, you will use dictionary methods to access and display dictionary elements.
Exercise 30 – accessing a dictionary using dictionary methods
In this exercise, you will learn how to access a dictionary using dictionary methods. The goal of this exercise is to print the order values against the item while accessing dictionary methods:
- Open a new Jupyter Notebook.
- Enter the following code in a new cell:
album_sales = {'barbara':150, 'aretha':75,
'madonna':300, 'mariah':220}
print( album_sales.values())
print(list( album_sales.values()))
The output is as follows:
dict_values([150, 75, 300, 220])
[150, 75, 300, 220]
The values()
method in this code returns an iterable object. To use the values straight away, you can wrap them in a list directly.
- Now, obtain a list of keys in a dictionary by using the
keys()
method:print(list(album_sales.keys()))
The output is as follows:
['barbara', 'aretha', 'madonna', 'mariah']
- Although you can’t directly iterate a dictionary, you can loop through the dictionary by using the
items()
method, as in the following code snippet:for item in album_sales.items():
print(item)
The output is as follows:
('barbara', 150)
aretha75('madonna', 300)
('mariah', 220)
In this exercise, you created a dictionary, accessed the keys and values of the dictionary, and looped through the dictionary.
The last step, showing the dictionary keys and values in parentheses, presents a new Python type, a tuple, as explained in the next section.