[Tutor] How to print corresponding keys in Dictionary

Alan Gauld alan.gauld at btinternet.com
Mon Oct 24 20:00:50 CEST 2011

On 24/10/11 14:18, Dave Angel wrote:

> 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.

For fun:

def getKeys(aDict, aValue):
     return [key for key,val in aDict if val == aValue]


Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list