11.5. Multiple Assignment with Dictionaries¶
By combining items
, tuple assignment, and for
,
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 key
and
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).
- [(4, 'd'), (10, 'a'), (15, 'b'), (17, 'c')]
- Incorrect! Remember, key-value pairs aren't in any particular order. Try again.
- [('a', 10), ('b', 15), ('c', 17), ('d', 4)]
- Incorrect! Remember, key-value pairs aren't in any particular order. Try again.
- There will be no particular order
- Correct! When running this type of iteration, we are left with a hash key order, meaning there is no particular order.
11-9-1: How will the contents of list “lst” be ordered after the following code is run?
d = {'a': 10, 'b': 15, 'c': 17, 'd': 4}
lst = []
for key, val in d.items():
lst.append( (val, key) )
print(lst)
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
list of (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.