Harold Nelson
4/5/2018
The class dictionary has an items method. Let’s see what it produces.
## <class 'dict_items'>
## dict_items([('Tom', 1), ('Dick', 2), ('Harry', 3)])
Note that the items method doesn’t exactly return a list, but it’s clearly almost one. We can get a list version by using list()
Doodle Take a few minutes to make your own example.
## <class 'list'>
## [('Tom', 1), ('Dick', 2), ('Harry', 3)]
Note that it is a list of tuples. We can sort this list because tuples are comparable. This is useful because dictionaries can’t be put in a sorted order.
## {'Tom': 1, 'Dick': 2, 'Harry': 3}
## [('Dick', 2), ('Harry', 3), ('Tom', 1)]
Doodle Take a few minutes to catch up.
We can use multiple assignment and iterate through this list to swap the keys and the values in the tuples.
## [(2, 'Dick'), (3, 'Harry'), (1, 'Tom')]
Since we have a list of reversed items from the dictionary, we could make a new dictionary from this list of tuples.
## {2: 'Dick', 3: 'Harry', 1: 'Tom'}
This is convenient. We can use this new dictionary for reverse lookup.
## 1
## Tom
Doodle Play with your own example.
Here’s a kind of “do nothing” in a complicated way.
## Tom
Would this always work? What condition would guarantee that a dictionary is invertible? Why is the squaring of real numbers not invertible?
Doodle Create an example by adding Curly to d and rerunning everything.