Home > Software engineering >  Python return key of dictionary depending on max value, but only where part of key = x
Python return key of dictionary depending on max value, but only where part of key = x

Time:03-07

I have a dictionary in Python:

dict = {("s1", "a1"):1,("s1", "a2"):2,("s3", "a3"):3,("s1", "a3"):1}

Where key is a list(s, a) and value is an integer, so:

dict = {(s, a), i}

I want to pass in a specific s and return a where i is highest.

In the example above, I would expect to recieve "a2" if I passed in "s1".

So far I have the following:

print(max(dict, key=dict.get("s1"))[1])

However this is returning s3. How do I get this to work?

CodePudding user response:

I would filter the dictionary first to only get items with a valid key and then find the key with the maximum value like this:

filtered_dict = {k:v for k, v in d.items() if k[0] == 's1'}
result = max(filtered_dict, key=filtered_dict.get)[1]
print(result)

Output:

a2

CodePudding user response:

The structure of the data is not the ideal one for your given use-case. But if you have no other option, you need to visit every single element in the dict.

You visit each element once:

current_max = -999
result = None
for (k1,k2), value in dict.items():
    if k1=="s1" and value > current_max:
        result = k2
        current_max = value
  • Related