'How can I get the max value from specific key in nested dictionary
I have this dictionary and I want to get the max value of the ratio key only
I did this:
company_dict = {0: {'link': 'www.facebook.com', 'ratio': 0.91, 'size': 3},
1: {'link': 'www.google.com', 'ratio': 0.92, 'size': 4}}
max_value = 0
for key, value in company_dict.items():
for k, v in value.items():
if k == 'ratio':
if v > max_value:
max_value = v
print(max_value)
Output: 0.92
Is there a better way ?
Solution 1:[1]
This also gives you the entire dictionary in addition to the max ratio:
best_company = max(company_dict.values(), key=lambda d: d["ratio"])
best_ratio = best_company["ratio"]
Solution 2:[2]
Short answer:
max(item['ratio'] for item in company_dict.values())
A bit more info:
You should not iterate through all items to get one of them, like this:
for k, v in value.items():
if k == 'ratio':
You can achieve the same with:
v = value['ratio']
Also, you don't need to implement your own logic to find the maximum, because there is the built-in function max.
So, what I did is, I took only the values of all items in company_dict:
company_dict.values()
Then, I took only the 'ratio' from each of them:
item['ratio'] for item in ...
And then I just called max for all of those ratio values.
Solution 3:[3]
You can use the key keyword argument of the max function in combination with a lambda.
company_dict = {0: {'link': 'www.facebook.com', 'ratio': 0.91, 'size': 3},
1: {'link': 'www.google.com', 'ratio': 0.92, 'size': 4}}
max_key = max(company_dict, key=lambda x: company_dict[x]['ratio'])
print(company_dict[max_key]['ratio'])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mateen Ulhaq |
| Solution 2 | zvone |
| Solution 3 | Lau |
