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

Find maximum value in a list of dicts

I’m new to Python, and I’ve been stuck at one point for several days now.

There is a list of dicts like this one:

dd = [{'prod': 'White', 'price': '80.496'}, {'prod': 'Blue', 'price': '9.718'}, {'prod': 'Green', 'price': '7161.3'}]

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

I need to output the value in prod based on the maximum value of the price.

Here is the desired result:
Green

I have tried many ways based on information I found on SO:

dd = [{'prod': 'White', 'price': '80.496'}, {'prod': 'Blue', 'price': '9.718'}, {'prod': 'Green', 'price': '7161.3'}]
L = [v for v in dd if v['price']==max([u['price']for u in dd])][0]['prod']
print(L)

Output:
Blue

(Almost correct, but "Blue" does not have the maximum value of the price!)

dd = [{'prod': 'White', 'price': '80.496'}, {'prod': 'Blue', 'price': '9.718'}, {'prod': 'Green', 'price': '7161.3'}]
L = max(dd, key=lambda x:x['price'])
print(L)

Output:
{'prod': 'Blue', 'price': '9.718'}

dd = [{'prod': 'White', 'price': '80.496'}, {'prod': 'Blue', 'price': '9.718'}, {'prod': 'Green', 'price': '7161.3'}]
L = max(e['price'] for e in dd)
print(L)

Output:
9.718

from operator import itemgetter
dd = [{'prod': 'White', 'price': '80.496'}, {'prod': 'Blue', 'price': '9.718'}, {'prod': 'Green', 'price': '7161.3'}]
L = max(map(itemgetter('price'), dd))
print(L)

Output:
9.718

dd = [{'prod': 'White', 'price': '80.496'}, {'prod': 'Blue', 'price': '9.718'}, {'prod': 'Green', 'price': '7161.3'}]
seq = [x['price'] for x in dd]
L = max(seq)
print(L)

Output:
9.718

In all cases, the maximum value is 9.718 and not 7161.3. How can I fix this? I’m using MS Visual Studio running Python 3.9.

>Solution :

You need to convert the price values to floats for the key parameter:

max(dd, key=lambda x: float(x['price']))['prod']

This outputs:

Green
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