繁体   English   中英

Python - 按值中的第二项对嵌套字典进行排序

[英]Python - Sort nested dictionary by the second item in the value

我有一个这样的字典:

{'xxx':['xxx', 0], 'yyy':['yyy', 2], 'zzz':['zzz', 3]}

我想通过每个键的值中的第二项从大到小对字典进行排序,所以我想要的结果是这样的:

{'zzz':['zzz', 3], 'yyy':['yyy', 2], 'xxx':['xxx', 0]}

有没有办法做到这一点? 谢谢! 请注意,可能存在具有相同值的字典项

在python版本中, CPython3.6是有序的( CPython3.6 m Python3.7+ )使用反向激活sorted和自定义key

>>> d = {'xxx':['xxx', 0], 'yyy':['yyy', 2], 'zzz':['zzz', 3]}
>>> d = dict(sorted(d.items(), reverse=True, key=lambda x: x[1][1]))
>>> d
{'zzz': ['zzz', 3], 'yyy': ['yyy', 2], 'xxx': ['xxx', 0]}

如果不是( Python3.5或更低版本),请使用OrderedDict

>>> from collections import OrderedDict
>>> d = {'xxx':['xxx', 0], 'yyy':['yyy', 2], 'zzz':['zzz', 3]}
>>> d = OrderedDict(sorted(d.items(), reverse=True, key=lambda x: x[1][1]))
>>> d
OrderedDict([('zzz', ['zzz', 3]), ('yyy', ['yyy', 2]), ('xxx', ['xxx', 0])])

Python中的dicts 按插入顺序排序 (对于Python> = 3.7),因此它们无法真正按照list可以排序的方式进行排序。 如果您想要可排序性,则应使用其他容器。

然而,对于Python> = 3.7(虽然它可以在CPython 3.6中工作),您可以从原始dict构建的tuples的排序list中创建一个新字典:

data = {'xxx':['xxx', 0], 'yyy':['yyy', 2], 'zzz':['zzz', 3]}
result = dict(sorted(data.items(), reverse=True, key=lambda p: p[1][1]))
>>> d = {'xxx':['xxx', 0], 'yyy':['yyy', 2], 'zzz':['zzz', 3]} >>> sorted(d.items(), key=lambda kv: kv[1][1], reverse=True) [('zzz', ['zzz', 3]), ('yyy', ['yyy', 2]), ('xxx', ['xxx', 0])]

我的朋友你可以使用排序方法:

尝试这个:

x  = {'xxx':['xxx', 0], 'yyy':['yyy', 3], 'zzz':['zzz', 2],'aaa':['aaa',1]}

newlist=sorted(x.items(), key=lambda kv: kv[1][1], reverse=True)
print (newlist) 

输出:

[('yyy', ['yyy', 3]), ('zzz', ['zzz', 2]), ('aaa', ['aaa', 1]), ('xxx', ['xxx', 0])]

新列表类型是列表。

如果你想要字典简单使用dict()如下:

newlist = dict(sorted(x.items(), key=lambda kv: kv[1][1], reverse=True))

输出: {'yyy': ['yyy', 3], 'zzz': ['zzz', 2], 'aaa': ['aaa', 1], 'xxx': ['xxx', 0]}

希望这个帮助

暂无
暂无

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

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