【问题标题】:Sorting list with 3-nested dictionaries by value按值对具有 3 个嵌套字典的列表进行排序
【发布时间】:2020-11-26 19:23:39
【问题描述】:

Sort list of nested dictionaries by value上的答案 不适用于更多嵌套数据,例如

[
    {
        "primary_key": 228282,
        "success": "YES",
        "date": "2020-10-09T10:10:33.123456",
        "spec": "text text text",
        "details": {
                    "quality": "228.33",
                    "measure": {
                        "title": "kilo",
                        "sign": "kg"
                }
            },
        "address_from": "NY",
        "address_to": "CA",
    },
    
    ...
    
]

如果我想按“日期”排序,则会出现错误:

    [item for item in lis if isinstance(item['date'], str)],
KeyError: 'date'

这种情况下如何按日期排序?

https://www.dropbox.com/s/2wc44gv9puwjd8t/228.json?dl=0 我有 .json 文件。我的尝试:

import json

with open("operations.json", "r", encoding='utf-8') as read_file:
    lis = json.load(read_file)
    print(lis)

print(
    sorted(
        [item for item in lis if isinstance(item['date'], str)],
        key=lambda i: i['date']
    )
)

【问题讨论】:

  • 这对我来说运行良好。您能否发布完整代码并仔细检查列表中的每个字典是否有一个名为“日期”的键?
  • 您的代码有效。请edit该问题添加可重现的示例。
  • @Norrius:完成。

标签: python json dictionary nested


【解决方案1】:

如果operations.json中有items没有日期键,你可以定义一个默认值(例如None):

import json

with open("operations.json", "r", encoding='utf-8') as read_file:
    lis = json.load(read_file)

print(
    sorted(
        [item for item in lis if isinstance(item.get('date', None), str)],
        key=lambda i: i['date']
    )
)

输出:

[{'primary_key': 228282, 'success': 'YES', 'date': '2020-10-09T10:10:33.123456', 'spec': 'text text text', 'details': {'quality': '228.33', 'measure': {'title': 'kilo', 'sign': 'kg'}}, 'address_from': 'NY', 'address_to': 'CA'}]

说明: item.get('date', None),尝试访问date,如果不可用,请使用None

【讨论】:

    猜你喜欢
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    • 2016-04-30
    • 2022-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多