Tarmiz Elyes
Tarmiz Elyes

Reputation: 3

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 ?

Upvotes: 0

Views: 186

Answers (3)

zvone
zvone

Reputation: 19382

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.

Upvotes: 1

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27271

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"]

Upvotes: 0

Blurred0993
Blurred0993

Reputation: 153

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'])

Upvotes: 0

Related Questions