Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Get key of nested dictionary with highest value for attribute

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading