11.5. Multiple Assignment with Dictionaries¶
items, tuple assignment, and
you can make a nice code pattern for traversing the keys and values of a
dictionary in a single loop:
for key, val in list(d.items()): print(val, key)
This loop has two iteration variables because
items returns a list of tuples and
key, val is
a tuple assignment that successively iterates through each of the
key-value pairs in the dictionary.
For each iteration through the loop, both
value are advanced to the next key-value pair in the
dictionary (still in hash order).
The output of this loop is:
10 a 22 c 1 b
Again, it is in hash key order (i.e., no particular order).
If we combine these two techniques, we can print out the contents of a dictionary sorted by the value stored in each key-value pair.
To do this, we first make a list of tuples where each tuple is
(value, key). The
items method would give us a
(key, value) tuples, but this time we want to sort
by value, not key. Once we have constructed the list with the value-key
tuples, it is a simple matter to sort the list in reverse order and
print out the new, sorted list.
By carefully constructing the list of tuples so that the value is the first element of each tuple and the key is the second element, we can sort our dictionary contents by value.
Construct a block of code to iterate through the items in dictionary d and print out its key-value pairs.
Write code to create a list called ‘lst’ and add the key-value pairs of dictionary d to list lst as tuples. Sort list lst by the values in descending order.