【问题标题】:How do I print all unique keys among dictionaries within a list?如何打印列表中字典之间的所有唯一键?
【发布时间】:2020-02-16 22:00:29
【问题描述】:

从 JSON 文件 (Abbreviated example JSON file) 读取后,我有一个名为“liveData.plays.allPlays”的列表,其中包含许多具有键值对的字典。字典中的键相似,但有些有额外的键。我想打印所有唯一键,最终目标是在 CSV 文件中写入标题行时将它们用作字段名。我还需要将相应的值作为行写入 CSV 文件的下方。

我可以使用以下代码和整数 0 的操作来打印任何单个 dict 中的所有键:

with open('nhlbigtest2.json', 'r') as read_file:
        data = json.load(read_file)
        for k in data["liveData.plays.allPlays"][0].keys():
            print(k)

这会产生:

about.dateTime
about.eventId
about.eventIdx
about.goals.away
about.goals.home
about.ordinalNum
about.period
about.periodTime
about.periodTimeRemaining
about.periodType
result.description
result.event
result.eventCode
result.eventTypeId

我可以将整数 0 操作为一个范围还是这个任务需要不同的方法? (使用 Python 3.7)

【问题讨论】:

    标签: python json python-3.x dictionary


    【解决方案1】:

    set 是一种旨在保存唯一值的数据结构。您可以遍历您的字典列表,并 update 一组包含每个字典的键:

    unique_keys = set()
    for game_dict in data["liveData.plays.allPlays"]:
        unique_keys.update(game_dict.keys())
    

    当您将数据写成 CSV 文件时,我建议使用 the csv.DictWriter class。您可以将一系列字段名传递给它(例如,上面的键的set,可能会重新排序并放入列表中),它会为每个字段写出列。如果给定字典没有特定键,则 CSV 文件中的行将为该列留一个空白,但您可以使用 restval 参数自定义它(如果您愿意,可以放置 'N/A' 或其他内容) .

    【讨论】:

    • 赞成。或者,作为集合理解unique_keys = {k for d in data["liveData.plays.allPlays"] for k in d}
    猜你喜欢
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 2018-05-16
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多