Home > Back-end >  Python Get key of nested dictionary with highest value for attribute
Python Get key of nested dictionary with highest value for attribute

Time:04-15

I have a problem. In my code, I have the following dictionary:

{1: {'amount': 40.0, 'quantity': 0}, 2: {'amount': 40.0, 'quantity': 0}, 3: {'amount': 40.0, 'quantity': 0}, 4: {'amount': 40.0, 'quantity': 0}, 5: {'amount': 41, 'quantity': 0}, 6: {'amount': 40.0, 'quantity': 0}, 7: {'amount': 40.0, 'quantity': 0}, 8: {'amount': 40.0, 'quantity': 0}, 9: {'amount': 40.0, 'quantity': 0}, 10: {'amount': 40.0, 'quantity': 0}}

Out of this dictionary, I need to grab the key of the inner dictionary with the greatest amount. In my case, that should be 5. I found a lot about things like this, but nothing about nested dictionaries.

I came up with something like this:

max(int(i['amount']) for i in dict.values())

But this returns the highest amount. I need to return the key of that dictionary with that amount. How can I achieve what I want?

CodePudding user response:

You can find the maximum among the keys of your dictionary, comparing based on a custom key parameter that retrieves the amount corresponding to the key:

result = max(data.keys(), key=lambda x: data[x]['amount'])

print(result)

CodePudding user response:

Perhaps you could check if the value is equal to the max and then save the key, e.g.,:

[k for k, v in dict.items() if v == max(int(v['amount'])]

This will give you a list of all the keys with the max-value (if multiple share a max)-- so to just get one you could index the 0th element of it.

  • Related