[Tutor] How to print corresponding keys in Dictionary

Dave Angel d at davea.name
Mon Oct 24 15:18:14 CEST 2011

On 10/24/2011 09:10 AM, Praveen Singh wrote:
> In Dictionary-
> How to print corresponding keys if the values of dictionary is given??
> -d={'a':1,'b':2,'c':3}
> -i can print the corresponding values by using get() method-
> - d.get('a')
> -1
> What if i have to print reverse???
A dictionary can be viewed as a mapping between keys and values, where 
you supply a key, and the dictionary quickly finds the corresponding 
value.  To do the reverse, you have to construct the code yourself and 
it will be much smaller, if there are many items.

For example (untested):

d = {"a", 1, "b":2, "c":3, "d":2}

def getkey(dictionary, value):
      for key, val in dictionary.items():
            if val == value:
                   return key

Note that if there are multiple keys with the same value, my function 
would get only the first.  It wouldn't be hard to modify the function to 
return a list of matching keys.



More information about the Tutor mailing list