simple question about dictionaries

Jeff jeffober at
Mon Jul 21 14:01:40 CEST 2008

On Jul 21, 7:35 am, skazhy <ska... at> 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?
> somehting like this:
> dict = { "key1"=100,"key2"=200,"key3"=300}
> a = input()
> print 'the key of inputted value is', dict['a']
> this syntax of course is wrong, but i hope you got the point..
> thanks in advance!

I don't think there is a built-in that retrieves dict keys by value,
but if the dictionary were small enough, you could search the list of
key/value pairs returned by dict.items().  You can also iterate
through all pairs with dict.iteritems(), which returns an iterator.
Something like:

def key_by_value(dct, val):
  for k, v in dct.iteritems():
    if v == val:
      return v
  throw KeyError('%s not found' % str(val))

More information about the Python-list mailing list