【问题标题】:Sort dictionary whose value is in the form of list of dictionary排序字典,其值为字典列表的形式
【发布时间】:2020-06-30 09:19:22
【问题描述】:

对字典列表形式的字典进行排序。

我有类似的东西:

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,还是想要一个所有值都已排序的列表?
  • 我只想要字典形式的输出
  • 你能得到确切的预期输出吗?
  • 您尝试对它进行什么排序和输出? minimal reproducible example?什么地方出了错?您的日期是文本,而不是日期时间 - 至于日期格式:不可能仅通过字符串比较对其进行排序。您如何对其进行转换以使其具有可比性?如果字典里面只有 1 个字典,为什么你的值列表是字典 - 里面可能有超过 1 个字典吗?如果里面有超过 1 个,使用哪个日期来排序?
  • 每个值列表是只有一个字典还是可以有多个(即您只在列表中显示单个字典)?

标签: python list python-2.7 sorting dictionary


【解决方案1】:

您可以将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'}])])

你可以阅读更多关于OrderedDicthere

我鼓励您使用python3.6 或更高版本,您可以从dict 中的广告订单中受益

【讨论】:

  • 多个内部字典呢?您只需按内部字典列表中的第一个字典排序。问题不清楚。
  • 好吧,OP可能会添加细节,但至少我可以帮助提供数据
猜你喜欢
  • 2011-02-22
  • 1970-01-01
  • 2020-04-30
  • 2011-09-23
  • 1970-01-01
  • 2012-03-03
  • 1970-01-01
相关资源
最近更新 更多