'Minimum value from a dictionary based on value in secondary list
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?
Solution 1:[1]
I would do this:
min(lst, key=dic.get)
Solution 2:[2]
Try:
k = min(dic.keys() & lst, key=dic.get)
print(k)
Prints:
Boston
Solution 3:[3]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dennis |
| Solution 2 | Andrej Kesely |
| Solution 3 | BrokenBenchmark |
