Wednesday, March 26, 2008

Python: How to find a list of keys for a given value in a dictionary

Here is a straight-forward, easy to understand way to find a list of keys in a dictionary for a given value (that may or may not be in the dictionary)

def GetListOfKeysForGivenValueInDict(dictionary,value):
  keys = []
  for k,v in dictionary.items():
    if v == value:
      keys.append(k)
  return keys

usage:


dictionary = {1:2,3:4,5:4}
value = 4
keys_list = GetListOfKeysForGivenValueInDict(dictionary, value)
print keys_list


result:


[3,5]

No comments: