[Tutor] Dictionary Question

Alan Gauld alan.gauld at yahoo.co.uk
Mon May 2 18:39:18 EDT 2016


On 02/05/16 22:55, isaac tetteh wrote:
> 
> For some reason i cant find reply all . But try this 
> for key, value in mydic.items():
>       If A==value:
>            Print key

or as a function:

def findKey(dct, val):
   for k,v in dct.items():
      if v == val:
         return k

mydic = {"A: "Apple", "B": "Banana"}

print( findKey(mydic,'Apple') )   # -> 'A'

The problem is that while keys are unique, values
might not be, so what do you do if multiple keys
share the same value?

You could use a comprehension:

def findKeys(dct,val):
    keys = [k for k,v in dct.items() if v == val]
    return keys

But if you are only interested in one of them then
it's down to you to figure out which!

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list