python字典基于值以降序排序 [英] python dictionary sorting in descending order based on values

查看:1204
本文介绍了python字典基于值以降序排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据子关键字key3的值以降序对字典d进行排序.见下文:

I want to sort this dictionary d based on value of sub key key3 in descending order. See below:

d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
      '124': { 'key1': 6, 'key2': 56, 'key3': 6 },
      '125': { 'key1': 7, 'key2': 44, 'key3': 9 },
    }

所以最终的字典看起来像这样.

So final dictionary would look like this.

d = { '125': { 'key1': 7, 'key2': 44, 'key3': 9 },
      '124': { 'key1': 6, 'key2': 56, 'key3': 6 },
      '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
    }

我的方法是从d形成另一个字典e,它的键将是key3的值,然后使用reversed(sorted(e)),但是由于key3的值可以相同,所以字典e丢失了一些键及其键价值观.有道理吗?

My approach was to form another dictionary e from d, whose key would be value of key3 and then use reversed(sorted(e)) but since value of key3 can be same, so dictionary e lost some of the keys and their values. makes sense?

我如何才能做到这一点?这不是经过测试的代码.我只是想了解逻辑.

How I can accomplish this? This is not a tested code. I am just trying to understand the logic.

推荐答案

Dictionaries do not have any inherent order. Or, rather, their inherent order is "arbitrary but not random", so it doesn't do you any good.

用不同的术语来说,您的de将是完全等效的字典.

In different terms, your d and your e would be exactly equivalent dictionaries.

您可以在这里使用 OrderedDict :

What you can do here is to use an OrderedDict:

from collections import OrderedDict
d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
      '124': { 'key1': 6, 'key2': 56, 'key3': 6 },
      '125': { 'key1': 7, 'key2': 44, 'key3': 9 },
    }
d_ascending = OrderedDict(sorted(d.items(), key=lambda kv: kv[1]['key3']))
d_descending = OrderedDict(sorted(d.items(), 
                                  key=lambda kv: kv[1]['key3'], reverse=True))

原始的d具有某些任意顺序. d_ascending具有您在原始d中所具有的思维顺序,但没有.并且d_ascending具有您想要的e顺序.

The original d has some arbitrary order. d_ascending has the order you thought you had in your original d but didn't. And d_ascending has the order you want for your e.

如果您真的不需要使用e作为字典,则只希望能够以特定顺序遍历d的元素,则可以简化此操作:

If you don't really need to use e as a dictionary, you just want to be able to iterate over the elements of d in a particular order, you can simplify this:

for key, value in sorted(d.items(), key=lambda kv: kv[1]['key3'], reverse=True):
    do_something_with(key, value)


如果要在所有更改中以排序的顺序维护字典,而不是OrderedDict,则需要某种排序的字典.您可以在PyPI上找到许多选项,一些选项在树的顶部实现,其他选项在OrderedDict的顶部,并根据需要对其进行重新排序,等等.


If you want to maintain a dictionary in sorted order across any changes, instead of an OrderedDict, you want some kind of sorted dictionary. There are a number of options available that you can find on PyPI, some implemented on top of trees, others on top of an OrderedDict that re-sorts itself as necessary, etc.

这篇关于python字典基于值以降序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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