繁体   English   中英

在Python中,如何通过内部dict中的键对字典中的dict排序

[英]In Python, how to sort a dict inside a dict by a key within the inner dict

我有一个键/值形式的数据集:

setlist = {{'135350258120342034': {'title':'The Matrix'}
          {'235350258120342034': {'title':'The Godfather'}
          {'335350258120342034': {'title':'Atonement'}
          }

如何按“键”的值对集合列表排序,“键”是字典中的一个字典?

>>> sorted(setlist.items(),key=lambda x:x[1]['title'])
[('335350258120342034', {'title': 'Atonement'}), ('235350258120342034', {'title': 'The Godfather'}), ('135350258120342034', {'title': 'The Matrix'})]

您不能,字典无法排序。

您可以做的是将外部字典的键移动到内部字典,然后将其粘贴在列表中,并通过.sort()使用自定义函数

如果要按排序顺序遍历列表,则需要以下内容:

for key, value in sorted(setlist.items(), key = lambda x: x[-1]['title']):
   pass

暂无
暂无

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

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