【问题标题】:Sort a dictionary by multiple keys that represent the same value按表示相同值的多个键对字典进行排序
【发布时间】:2019-07-16 10:09:00
【问题描述】:

我有一个字典列表,每个字典中有一个日期(datetime.datetime 对象),但在某些情况下它与键 "created_at" 相关联,在其他情况下与 "notification_timestamp" 相关联。

data = [{'foo':'bar', 'created_at':'00:15:20 04/05/2019'},{'foo2':'bar2', 'notification_timestamp':'00:35:20 04/05/2019'}]

我知道我可以只重命名键,但我需要一个高效/可扩展的解决方案来按这些键排序此列表。

我尝试过data = data.sort(key=operator.itemgetter("created_at", "notification_timestamp"), reverse=True),但它会抛出以下错误:

Exception Type: KeyError at /v1/my_script
Exception Value: 'notification_timestamp'

大概是因为不是所有的字典都有这个键。

我确定我的变量的数据类型,这个脚本的输出

for d in data:
    if d.get("created_at", False):         
        print("CREATED AT TYPE: ", type(d.get("created_at")))
    if d.get("notification_timestamp", False):
        print("notification_timestamp TYPE: ", type(d.get("notification_timestamp")))

CREATED AT TYPE:  <class 'datetime.datetime'>
notification_timestamp TYPE:  <class 'datetime.datetime'>

感谢所有帮助

【问题讨论】:

    标签: python sorting dictionary


    【解决方案1】:

    感谢@Rakesh 向我展示了在这种情况下使用x.get() 的可能性,我找到了解决方案:

    data.sort(key=lambda x: x.get("created_at", x.get("notification_timestamp", None)), reverse=True)

    【讨论】:

      【解决方案2】:

      尝试使用dict.get

      例如:

      data = [{'foo':'bar', 'created_at':'00:15:20 04/05/2019'},{'foo2':'bar2', 'notification_timestamp':'00:35:20 04/05/2019'}]
      data.sort(key=lambda x: x.get("created_at", x.get("notification_timestamp")))  #Thanks AbdulNiyasPM & h4z3
      print(data)
      

      【讨论】:

      • 我不知道你会这样,这很有帮助,谢谢!
      • 我试过了,但它给了我这个错误而不是'&lt;' not supported between instances of 'datetime.datetime' and 'str',但我知道与键关联的两个值都是datetime.datetime。这可能是get的结果吗?当密钥不存在时,它可能返回一个 str 吗?如果是这样,有没有办法覆盖它?
      • 不,我刚刚打印了每个对象的type(),它们都是datetime.datetime
      • @h4z3 有没有办法以更有用的方式使用x.get()?我可以在get 中添加get 吗?
      • 哦,我很抱歉这是一个错字...@AbdulNiyasPM @h4z3。谢谢
      猜你喜欢
      • 2015-04-06
      • 2023-01-22
      • 2019-12-30
      • 2016-03-14
      • 1970-01-01
      • 1970-01-01
      • 2013-11-02
      • 2013-09-16
      • 1970-01-01
      相关资源
      最近更新 更多