Dictionaries and Tuples

Harold Nelson

4/5/2018

The Items Method

The class dictionary has an items method. Let’s see what it produces.

d = {"Tom":1,"Dick":2,"Harry":3}
i = d.items()
print(type(i))
## <class 'dict_items'>
print(i)
## 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.

li = list(i)
print(type(li))
## <class 'list'>
print(li)
## [('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.

print(d)
## {'Tom': 1, 'Dick': 2, 'Harry': 3}
li.sort()
print(li)
## [('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.

liRev = []
for key, value in li:
   liRev.append((value,key))
print(liRev)   
## [(2, 'Dick'), (3, 'Harry'), (1, 'Tom')]

A Reversed Dictionary?

Since we have a list of reversed items from the dictionary, we could make a new dictionary from this list of tuples.

rd = dict(liRev)
print(rd)
## {2: 'Dick', 3: 'Harry', 1: 'Tom'}

This is convenient. We can use this new dictionary for reverse lookup.

print(d["Tom"])
## 1
print(rd[1])
## Tom

Doodle Play with your own example.

Here’s a kind of “do nothing” in a complicated way.

print(rd[d["Tom"]])
## 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.