通过内部“属性"对字典排序.字典键值

编程入门 行业动态 更新时间:2024-10-27 08:33:21
本文介绍了通过内部“属性"对字典排序.字典键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我使用for循环和以下代码创建了字典:

I created a dictionary using a for-loop and this code:

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

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

Previously my dictionary was just players = {names: totals} and I could sort it using this code:

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

但是现在,由于我实现了内部的属性"字典,因此我收到一个错误,提示无法对字典进行比较.

But now since I implemented the inner "attribute" dictionary, I get an error saying comparisons can't be made on dictionaries.

TypeError:'<' 'dict'和'dict'实例之间不支持

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

那么我该如何修改排序方法以比较字典的值(roll_total值),并对我的玩家词典进行排序?

So how can I modify the sorting method to compare values of the dictionaries (the roll_total values), and have my players dictionary sorted?

推荐答案

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

That happens because you are comparing two dictionaries.Use:

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

lambda函数接收名称为x的键,然后根据玩家[x] ['roll_total']进行排序,而玩家[x] ['roll_total']基本上是玩家[name] ['roll_total'].

The lambda function receives the key of name as x and then sorts on the basis of players[x]['roll_total'] which is basically players[name]['roll_total'].

更多推荐

通过内部“属性"对字典排序.字典键值

本文发布于:2023-05-29 15:07:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/347282.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   键值   属性   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!