ubuntu2004
Dictionaries II - looping
Looping through a dictionary
We've seen how to loop through strings and lists. Now we will look at the ways of looping through a dictionary one item at a time.
The following code loops through the keys of our dictionary of white blood cells.
Notice that this code only loops through the keys. The values are ignored.
Looping through keys and values simultaneously
Often we want to loop through a dictionary and use or output each key:value pair. There are two of ways of doing this:
Loop through the keys and use them to get each item's value.
Loop through the items.
Let's look at these in turn.
1. Loop through the keys and use them to get each item's value
In the last Notebook we saw that to get the value of a key:value pair we use the notation dict_var[key]
. So we could modify the above code to output each key and its value like so:
2. Loop through items
A simpler and shorter way to write the above code is by looping through the items of the dictionary rather than just the keys.
There is some new notation. The line
loops through each item in the dictionary. But now there are two iterating variables: cell_type
which contains the key of the item, and diameter
which contains the value of the item.
This is a common way of looping over a dictionary when both the key and its value are needed.
Loop through sorted keys
We may want to loop through the keys in alphabetical or numerical order. This is achieved by using sorted()
which we came across in Notebook 12 when we looped through a sorted list.
Notice that the cell types are sorted alphabetically.
Loop through reverse sorted keys
The following code shows how to loop through the keys sorted in reverse alphabetical order.
We've added
into sorted()
.
Loop through sorted values: Advanced Python
Rather than loop through the dictionary sorted on keys we may want to loop through the dictionary sorted on their values, either alphabetically or numerically.
Notice that Small lymphocyte
comes first at 7.5 micrometers and Monocyte
comes last at 22.5 micrometers.
We won't explain here how this works as it is beyond the scope of this course.