the following is a list from a small blind auction program i am writing. After the last bid, I need to loop through all the bids in the list and print out the highest one with the name of the bidder. How can I go about that? Any help?
bids = [{'don': 200}, {'alex': 400}, {'peter': 550}]
You can use max
with a custom key function:
>>> next(iter(max(bids, key=lambda d: next(iter(d.values())))))
'peter'
The most annoying part of this is the next(iter(...))
part of extracting the key/value from the dictionary.
Is there any reason you use this datastructure rather than a simple dictionary like {'don': 200, 'alex': 400, 'peter': 550}
? In that case it would be easier:
>>> max(bids, key=lambda name: bids[name])
'peter'
You can sort the list according to the value in each dictionary and print out the last item:
bids = [{'don': 200}, {'alex': 400}, {'peter': 550}]
s = sorted(bids, key=lambda x:list(x.values())[0])
print(s[-1])
#{'peter': 550}
UPDATED:
bids = [{'don': 200}, {'alex': 400}, {'peter': 550}]
bids.sort(key=lambda x:list(x.values())[0], reverse=True)
print(f'The winner is {list(bids[0].keys())[0]} with a ${list(bids[0].values())[0]} bid.')
#The winner is peter with a $550 bid.
I think using {'name':'bidername','bid': bid} makes it so easy. After that u can sort it and take the last one or you can iterate on bids and find the highest bid.
bids = [{'name': 'don', 'bid': 200}, {'name': 'alex', 'bid': 400}, {'name': 'peter', 'bid': 550}]
print(sorted(bids, key=lambda x: x['bid']))
if you want to get only highest value.
bids = [{'don': 200}, {'alex': 400}, {'peter': 550}]
bidder = None
values = []
for bid in bids:
for k, v in bid.items():
values.append(v)
bidder = max(values)
print(bidder)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.