通过内部“属性"对字典排序.字典键值 [英] Sorting a dictionary by an inner "attribute" dictionary key-value

查看:103
本文介绍了通过内部“属性"对字典排序.字典键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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'].

这篇关于通过内部“属性"对字典排序.字典键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆