如何从嵌套在列表中的字典中获取最高值

How can I get the highest value from a dictionary nested in a list

以下是我正在编写的一个小型盲人拍卖程序的列表。在最后一次出价之后,我需要遍历列表中的所有出价,并打印出最高的出价者姓名。我该怎么做?有帮助吗?

bids = [{'don': 200}, {'alex': 400}, {'peter': 550}]

您可以将 max 与自定义键功能一起使用:

>>> next(iter(max(bids, key=lambda d: next(iter(d.values())))))
'peter'

最烦人的部分是从字典中提取 key/value 的 next(iter(...)) 部分。

你有什么理由使用这个数据结构而不是像 {'don': 200, 'alex': 400, 'peter': 550} 这样的简单字典吗?在那种情况下会更容易:

>>> max(bids, key=lambda name: bids[name])
'peter'

我认为使用 {'name':'bidername','bid': bid} 会变得非常简单。之后你可以对其进行排序并取最后一个,或者你可以迭代出价并找到最高出价。

bids = [{'name': 'don', 'bid': 200}, {'name': 'alex', 'bid': 400}, {'name': 'peter', 'bid': 550}]

print(sorted(bids, key=lambda x: x['bid']))

您可以根据每个字典中的值对列表进行排序并打印出最后一项:

bids = [{'don': 200}, {'alex': 400}, {'peter': 550}]
s = sorted(bids, key=lambda x:list(x.values())[0])
print(s[-1])

#{'peter': 550}

更新:

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 0 bid.

如果您只想获得最高价值。

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)