Home > front end >  get the key of the minimum value of a dictionary which in turn the key is in an array
get the key of the minimum value of a dictionary which in turn the key is in an array

Time:10-21

I want to get the key that has the minimum value in a given dictionary, but with the condition that this key is in a given list

for example this would be the dictionary.

dict = {
    's': 0,
    'y': 5,
    't': 8,
    'z': 7,
    'x': 9
}

and this is the list with the keys to be checked

list = ['y', 'z', 't', 'x'] 

I made this implementation, but I think it could be optimized or made in a more pythonic way.

a = float("inf")
for key in dict:
    if key in list:
        temp=a
        a = min(a,dict[key])
        if a < temp:
            minimum = key

CodePudding user response:

Use min with dct.get:

>>> min(lst, key=dct.get)
'y'
>>> 

This get's the minimum value in lst based o n the value of that key in the dct dictionary.

P.S. I renamed dict to dct and list to lst, so you don't override the variable names.

Edit:

As @Ch3steR mentioned, if there are any keys not in the dictionary that are in lst.

You could use:

min(lst, key=lambda x: dct.get(x, float('inf')))

Or you could use @Ch3steR's approach, with:

min(dct.keys() & lst, key=dct.get)
'y'

But I implemented my own type, named mydict, which you can use, it has dict inherited just it also has a __missing__ magic method definition, so it will give float('inf') (infinity) if the key doesn't exist. Let's say lst becomes:

lst = ['y', 'z', 't', 'x', 'key that does not exist']

Then you inherit mydict type:

mydict = type('mydict', (dict,), {'__missing__': lambda self, key: float('inf'),})

And now you can use __getitem__ directly:

>>> min(lst, key=mydict(dct).__getitem__)
'y'
>>> 

The same mydict type could be inherited with:

class mydict(dict):
    def __missing__(self, key):
        return float('inf')

And it would work too.

CodePudding user response:

Here is one approach using List Comprehension:

dict = {
    's': 0,
    'y': 5,
    't': 8,
    'z': 7,
    'x': 9
}
list = ['y', 'z', 't', 'x'] 
temp =min([j for i,j in dict.items() if i in list])     ##output - 5
res = [i for i,j in dict.items() if dict[i]==temp]      
print(*res)

Output:

y 
  • Related