简体   繁体   English

排序嵌套的python字典

[英]Sorting nested python dictionary

I have a python dictionary with the following format. 我有以下格式的python字典。

{'KEY': (NUMBER, [DATE1, DATE2]}

For example, {'a': (10, ['2010/04/11','2009/03/11'])} 例如, {'a': (10, ['2010/04/11','2009/03/11'])}

How can I sort this dictionary by the DATE1(the first element in the list)? 如何按DATE1(列表中的第一个元素)对字典进行排序?

EDIT 编辑

Can I sorted again when the date is the same? 日期相同时可以再次排序吗? For example. 例如。

{'a': (10, ['2010/04/11','2009/03/11'])}
{'b': (20, ['2010/04/11','2009/03/10'])}
{'c': (100, ['2009/01/01'])}

--> ->

{'b': (20, ['2010/04/11','2009/03/10'])} // this comes first as 20 > 10
{'a': (10, ['2010/04/11','2009/03/11'])}
{'c': (100, ['2009/01/01'])}

Dictionaries are unsortable. 字典无法排序。 If you want a sorted list of 2-tuples: 如果要2元组的排序列表:

sorted(D.iteritems(), key=lambda x: x[1][1][0])

Pass the expression to datetime.strptime() if you want it in date order instead of string order (not that there is a huge difference given the existing date format...). 如果希望按日期顺序而不是字符串顺序将表达式传递给datetime.strptime() (不是给定现有的日期格式有很大的不同...)。

If you're using Python 2.7 or later, you can use the new collections.OrderedDict class. 如果您使用的是Python 2.7或更高版本,则可以使用新的collections.OrderedDict类。 Along with Ignacio's code for doing the actual sorting, that should give you what you're looking for. 加上Ignacio进行实际排序的代码,它应该可以为您提供所需的内容。

Say that a is your current dictionary, then 假设a是您当前的字典,那么

OrderedDict(sorted(a.items(), key=lambda x: (x[1][1][0], -x[1][0])))

will return a sorted version. 将返回一个排序的版本。

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

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