gpt4 book ai didi

python - 按内部 "attribute"字典键值对字典进行排序

转载 作者:太空宇宙 更新时间:2023-11-04 02:19:42 24 4
gpt4 key购买 nike

我使用 for 循环和这段代码创建了一个字典:

players[name] = {'roll_total': player_roll, 'ante': None}

以前我的字典只是 players = {names: totals} 我可以使用以下代码对它进行排序:

players = [(k, players[k]) for k in sorted(players, key=players.get, reverse=True)]

但是现在,由于我实现了内部“属性”字典,我收到一条错误消息,指出无法对字典进行比较。

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

那么我如何修改排序方法来比较字典的值(roll_total 值),并让我的玩家字典排序?

最佳答案

发生这种情况是因为您正在比较两个词典。使用:

players = [(k, players[k]) for k in sorted(players, key=lambda x: players[x]['roll_total'], reverse=True)]

lambda 函数接收 name 的键作为 x,然后根据 players[x]['roll_total'] 进行排序,这基本上是 players[name]['roll_total']。

关于python - 按内部 "attribute"字典键值对字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51911734/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com