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

标签 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'

我需要改变什么?

最佳答案

您想使用列表理解或生成器表达式来仅遍历命中数:

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'

关于python - 如何从字典中找到最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55506507/

相关文章:

python - Django Python 数据库更新

python - 如何在 IntEnum 类主体中运行自定义代码

python - 创建一个字典列表,每一步仅修改一个值

python - Ansible 设置失败事实

Mysql 语法错误 - Backtics 无法解决它

for-loop - 如何通过管道输入 for 循环 Elixir

syntax - OCaml 的 `type a. a t` 语法

python - 密谋:如何在两个子图上使用相同的配色方案?

python - 我们何时以及为何使用 tf.reduce_mean?

C# 字典 ContainsKey 与 Keys.Any()