Most efficient way to find the key of the smallest value in a dictionary from a subset of the dictionary

StackOverflow https://stackoverflow.com/questions/21584601

  •  07-10-2022
  •  | 
  •  

Question

So given a list:

o = [1,2,4,6]

And a dictionary:

f = {1:10, 2:5, 3:1, 4:3, 5:7, 6:9}

What is the most efficient way to find the key in f that is associated with the lowest value in f where the key is also a memeber of the list o?

With the above list (o) and dictionary (f), I would be looking for key 4, while key 3 is associated with the value 1 and lower, 3 is not a member of list o.

Currently I am creating a dictionary of the subset of key pairs in want to check and then using min to get the value:

f_temp = dict((x,f[x]) for x in o)
current = min(f_temp, key=f_temp.get)

This does work but creating a new dictionary seems inefficient.

Using python 2.6 here hence the dict syntax with the dictionary comprehension.

Was it helpful?

Solution

You can use a dictionary view with set operations to select only keys from your input sequence:

min(f.viewkeys() & o, key=f.get)

In Python 3, all you need to use is:

min(f.keys() & o, key=f.get)

as the dict.keys() method now returns dictionary views.

Alternatively, you could use a key function that excludes keys you don't want to include:

set_o = set(o)
min(f, key=lambda k: f[k] if k in set_o else float('inf'))

I'm using a set here to make membership tests efficient. float('inf') (positive infinity) is guaranteed to always test larger than any other value.

Demo:

>>> o = [1, 2, 4, 6]
>>> f = {1: 10, 2: 5, 3: 1, 4: 3, 5: 7, 6: 9}
>>> min(f.viewkeys() & o, key=f.get)
4
>>> set_o = set(o)
>>> min(f, key=lambda k: f[k] if k in set_o else float('inf'))
4
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top