简体   繁体   English

python 3中嵌套字典的排序列表

[英]Sorting list of nested dictionaries in python 3

I am trying to sort a dictionary containing dictionaries.我正在尝试对包含字典的字典进行排序。 Here is that dictionary:这是那本字典:

mydict = {
  'b': {'play': 2, 'scratch': 5, 'face': 8},
  'c': {'do': 4, 'chew': 6},
  'a': {'wash': 1, 'drink': 10, 'give': 20, 'eat': 30}
}

I want the following result after sorting:排序后我想要以下结果:

{
  'a': {'eat': 30, 'give': 20, 'drink': 10, 'wash': 1},
  'b': {'face': 8, 'scratch': 5, 'play': 2},
  'c': {'chew': 6, 'do': 4}
}

I will appreciate if you tell me how to solve this issue.如果你告诉我如何解决这个问题,我将不胜感激。

Creating an ordered version of mydict创建 mydict 的有序版本

Let's start with your dictionary:让我们从你的字典开始:

>>> mydict = {
...   'b': {'play': 2, 'scratch': 5, 'face': 8},
...   'c': {'do': 4, 'chew': 6},
...   'a': {'wash': 1, 'drink': 10, 'give': 20, 'eat': 30}
... }

Ordinary dictionaries are unordered.普通字典是无序的。 Ordered dictionaries, however are available from the collections module:有序字典,但是可以从 collections 模块获得:

>>> from collections import OrderedDict

We can convert your dictionary to an ordered dictionary as follows:我们可以将您的字典转换为有序字典,如下所示:

>>> d = OrderedDict(sorted(mydict.items()))
>>> d
OrderedDict([('a', {'give': 20, 'drink': 10, 'eat': 30, 'wash': 1}), ('b', {'scratch': 5, 'play': 2, 'face': 8}), ('c', {'do': 4, 'chew': 6})])

As you can see above, d is ordered as we want.正如你在上面看到的, d是按照我们想要的顺序排序的。 Alternatively, we can look at just the keys and verify they are in the order that we want:或者,我们可以只查看密钥并验证它们的顺序是我们想要的:

>>> d.keys()
odict_keys(['a', 'b', 'c'])

In other ways, our ordered dictionary d behaves just like a regular dictionary:在其他方面,我们的有序字典d行为就像一个普通字典:

>>> d['a']
{'give': 20, 'drink': 10, 'eat': 30, 'wash': 1}

Ordering mydict by key while ordering the dictionaries inside it by value in descending order按键对 mydict 进行排序,同时按值按降序对其中的字典进行排序

If we want the dictionaries inside mydict to be sorted in descending order of value, we use an OrderedDict again:如果我们希望 mydict 中的字典按值的降序排序,我们再次使用 OrderedDict:

>>> mydict['a']
{'give': 20, 'drink': 10, 'eat': 30, 'wash': 1}
>>> OrderedDict(sorted(mydict['a'].items(), key=lambda v: -v[-1]))
OrderedDict([('eat', 30), ('give', 20), ('drink', 10), ('wash', 1)])

If we want to apply this ordering to all entries of mydict:如果我们想将此排序应用于 mydict 的所有条目:

>>> d = OrderedDict( sorted( (key1, OrderedDict(sorted(value.items(), key=lambda v: -v[-1]))) for (key1, value) in mydict.items()) )
>>> d
OrderedDict([('a', OrderedDict([('eat', 30), ('give', 20), ('drink', 10), ('wash', 1)])), ('b', OrderedDict([('face', 8), ('scratch', 5), ('play', 2)])), ('c', OrderedDict([('chew', 6), ('do', 4)]))])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM