python - 排序字典,其值为字典列表的形式
问题描述
排序一个字典,其值是字典列表的形式。
我有类似的东西:
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
都是一个列表,其中有一个 dict,其中有一个有效的'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
推荐阅读
- python - 使用 conda install pytorch=0.3.0 torchvision=0.2.0 cuda90 时的“包 _libgcc_mutex 冲突:”
- oracle - 如何在 OracleDB 中查看用户创建的表?
- nginx - 从子目录中请求文件时如何重写语言 uri。Nginx 码头工人
- reactjs - 将道具传递给 onClick 函数获取错误函数获取值字符串
- amazon-web-services - 使用 AWSForecast 在训练窗口快结束时缺失值
- c++ - 如何使用 lambda 替换 std::bind
- r - 计算每个类别(机器)的日期范围重叠的次数
- mysql - 如何将 3 个查询合二为一,并在每个表中加入并计数一行?
- email - 纯文本电子邮件无法显示非 ASCII 字符?
- r - 是否可以重命名列表中的多个列表名称?