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'}]
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.
CodePudding user response:
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