Jacob
Jacob

Reputation: 35

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?

Upvotes: 1

Views: 48

Answers (3)

Andrej Kesely
Andrej Kesely

Reputation: 195543

Try:

k = min(dic.keys() & lst, key=dic.get)
print(k)

Prints:

Boston

Upvotes: 1

Dennis
Dennis

Reputation: 2304

I would do this:

min(lst, key=dic.get)

Upvotes: 1

BrokenBenchmark
BrokenBenchmark

Reputation: 19252

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

Upvotes: 0

Related Questions