首页 > 解决方案 > 排序字典,其值为字典列表的形式

问题描述

排序一个字典,其值是字典列表的形式。

我有类似的东西:

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'}]}

我想要字典形式的输出

标签: pythonlistpython-2.7sortingdictionary

解决方案


您可以使用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


推荐阅读