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

时间:2019-04-04 01:17:13

标签: python dictionary syntax max

嗨,这是我第一次使用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'

我需要更改什么?

1 个答案:

答案 0 :(得分: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'