simple question about dictionaries

Fredrik Lundh fredrik at pythonware.com
Mon Jul 21 08:03:25 EDT 2008


skazhy wrote:

> hi, i am new to python, so i've a really simple question about
> dictionaries.
> if i have a dictionary and I make have an input after it (to input
> numbers) can i get the key of value that was in input?

A dictionary contains (key, value) pairs, and is optimized for quickly 
finding the value in a pair, if given the key.

> somehting like this:
> dict = { "key1"=100,"key2"=200,"key3"=300}

dict() is a built-in function; you're free to reuse the names of such 
functions as variable names in Python, but if you do, you won't be able 
to use those functions in that part of your program.  And in this case, 
the dict() built-in might be useful (see below):

> a = input()
> print 'the key of inputted value is', dict['a']
> 
> this syntax of course is wrong, but i hope you got the point..

Assuming that you want the *key* in Python's sense, for a given value, 
you can either loop over the dictionary (called D below):

     for k, v in D.items():
         if v == a:
             print 'the key of inputted value is', v
             break
     else:
         print "not found"

or create an reverse mapping and use that (you only have to do this 
every time the dictionary changes, of course), e.g.

     reverse_D = dict((D[k], k) for k in D)

     a = input()
     print "the key for value", a, "is", reverse_D[a]

(this doesn't work if you call your dictionary "dict", obviously.)

</F>




More information about the Python-list mailing list