如何从字典中找到最大值?

问题描述 投票:4回答:1

嗨,我第一次使用python

我有一本字典:

players= {"Gehrig":{"atBats":8061, "hits":2721},
 "Ruth":{"atBats":8399, "hits":2873},
 "Williams":{"atBats":7706, "hits":2654}}

我希望三位球员中的任何一位都能找到最多。

期望的输出:

The most hits by one of the
players was 2873.

我的意见:

max(players.hits())
maximum = max(players,key=players.get)
max(players,key=players.get)

但我只是得到如下错误:

TypeError: '>' not supported between instances of 'dict' and 'dict'

我需要改变什么?

python dictionary syntax max
1个回答
1
投票

您希望使用列表推导或生成器表达式来仅遍历命中数:

players= {"Gehrig":{"atBats":8061, "hits":2721},
 "Ruth":{"atBats":8399, "hits":2873},
 "Williams":{"atBats":7706, "hits":2654}}

max(player["hits"] for player in players.values())
# 2873

如果你想看看哪个玩家的点击率最高:

max(players.keys(), key=lambda p: players[p]["hits"])
# 'Ruth'
© www.soinside.com 2019 - 2024. All rights reserved.