gozzilli gozzilli - 2 months ago 6
Python Question

Python: get key with the least value from a dictionary BUT multiple minimum values

I'm trying to do the same as
Python: get key with the least value from a dictionary, where we want to get the key corresponding to the minimum value in a dictionary.

The best way appears to be:

min(d, key=d.get)


BUT I want to apply this on a dictionary with multiple minimum values:

d = {'a' : 1, 'b' : 2, 'c' : 1}


Note that the answer from the above would be:

>>> min(d, key=d.get)
'a'


However, I need both the two keys that have a minimum value, namely
a
and
c
.

What would be the best approach?

(Ultimately I want to pick one of the two at random, but I don't think this is relevant).

Answer

One simple option is to first determine the minimum value, and then select all keys mapping to that minimum:

min_value = min(d.itervalues())
min_keys = [k for k in d if d[k] == min_value]

For Python 3 use d.values() instead of d.itervalues().

This needs two passes through the dictionary, but should be one of the fastest options to do this anyway.

Using reservoir sampling, you can implement a single pass approach that selects one of the items at random:

it = d.iteritems()
min_key, min_value = next(it)
num_mins = 1
for k, v in it:
    if v < min_value:
        num_mins = 1
        min_key, min_value = k, v
    elif v == min_value:
        num_mins += 1
        if random.randrange(num_mins) == 0:
            min_key = k

After writing down this code, I think this option is of rather theoretical interest… :)

Comments