[Tutor] more dictionary fun
Daniel Yoo
dyoo@hkn.eecs.berkeley.edu
Tue, 6 Mar 2001 21:33:08 -0800 (PST)
On Wed, 7 Mar 2001 ewe2@can.org.au wrote:
> I have a dictionary in the form of {('A':(1,0)),('B':(2,1))} where the
> values are guaranteed to be unique. Given a specific value (e.g.
> (3,0)), how do i lookup the key?
Hmmm... usually, it goes the other way around: dictionaries can, given a
key, lookup a value really fast. If we have the value, and we're looking
for keys, it's a lot slower, but it can be done.
Dictionaries have a method called items() which give a list of key/value
tuples. For example:
###
>>> dict = {'a': (1,0), 'b': (2,1)}
>>> dict.items()
[('b', (2, 1)), ('a', (1, 0))]
###
So we can write a for loop that says:
for key, value in dict.items():
if value == (3,0):
print "We've found it with key", key
Another way to do it is to "invert" a dictionary. If we're positively
sure that the values are unique, we can write a dictionary_invert()
function that returns a new dictionary, where the keys are now the values
and vice versa:
###
def invert_dict(dict):
new_dict = {}
for key, value in dict.items():
new_dict[value] = key
return new_dict
###
Personally, I like the invert_dict() method, because it's reusable in many
other problems.
Hope this helps!