[英]Sort dictionary whose value is in the form of list of dictionary
排序字典,其值是字典列表的形式。
我有类似的东西:
myDict = {'First' :[{'Name':'Raj','Date':'28-March-2019 09:30'}],
'Second':[{'Name':'Ajay','Date':'12-April-2020 07:25'}],
'Third':[{'Name':'Jaya','Date':'12-April-2019 09:25'}]}
我想根据日期按升序对其进行排序。
预期输出:
myDict = {'First' :[{'Name':'Raj','Date':'28-March-2019 09:30'}],
'Third' :[{'Name':'Jaya','Date':'12-April-2019 09:25'}],
'Second':[{'Name':'Ajay','Date':'12-April-2020 07:25'}]}
我想要字典形式的输出
您可以将collections.OrderedDict
与内置函数sorted
:
from collections import OrderedDict
from datetime import datetime
OrderedDict(sorted(myDict.items(), key=lambda x: datetime.strptime(x[1][0]['Date'], '%d-%B-%Y %H:%M')))
此解决方案假定myDict
中的每个值都是一个列表,其中包含一个字典,其中包含一个有效的'Date'
键(如您提供的数据所示)
在 python2.7 字典插入顺序中不能保证,所以你不能得到你想要的输出,但是,你可以使用 OrderedDict
输出:
OrderedDict([('First', [{'Name': 'Raj', 'Date': '28-March-2019 09:30'}]),
('Third', [{'Name': 'Jaya', 'Date': '12-April-2019 09:25'}]),
('Second', [{'Name': 'Ajay', 'Date': '12-April-2020 07:25'}])])
您可以在此处阅读有关OrderedDict
更多信息
我鼓励你使用python3.6或更高版本,你可以从dict
的插入顺序中受益
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.