I have a list and a dictionary:
lst = ['Boston', 'Denver']
dic = {'Atlanta': 0, 'Boston':100, 'Denver':160}
I want to find the dictionary key that has the lowest value provided the key is in the list. In this case, I want to return 'Boston' rather than 'Atlanta' since it is not contained in the list. How would I search for the minimum value efficiently?
CodePudding user response:
I would do this:
min(lst, key=dic.get)
CodePudding user response:
You can use min()
with a key parameter that associates a value of inf
to any key that doesn't appear in the list:
min(dic.keys(), key=lambda x: dic[x] if x in lst else float('inf'))
This outputs:
Boston
CodePudding user response:
Try:
k = min(dic.keys() & lst, key=dic.get)
print(k)
Prints:
Boston