首页 > 解决方案 > 将 Python 字典中的 JSON 值累积为数组

问题描述

我有具有这种格式的 JSON 文件

{ 
"links": [
{"source":"0","target":"1","weight":1,"color":"white"},
{"source":"0","target":"2","weight":1,"color":"yellow"},
{"source":"0","target":"3","weight":1,"color":"white"},
]
}

我想收集所有这样target的单曲source

{"source": 0, "neighbors": ["1","2","3"]}neighbors收集的都在哪里target

这是我的代码

import json

with open("linksGr.json") as file:
    data = json.load(file)

collectDict = {}
for obj in data["links"]:
    if (collectDict["source"] == obj["source"]):
        collectDict["neighbour"] = obj["target"]

我只需要一种方法来为每个来源累积所有目标,而不是像我在这里所做的那样有多个来源

collectDict["source"] = obj["source"]
collectDict["neighbour"] = obj["target"]

任何帮助将不胜感激。我确信这里缺少一些基本概念和一种简单的方法。谢谢您的帮助。

标签: pythonjsondictionary

解决方案


如果我理解正确,您可以使用collections.defaultdict, 从源映射到目标列表,如下所示:

(我添加了一些数据以获得多个来源)

from collections import defaultdict

data = { 
"links": [
{"source":"0","target":"1","weight":1,"color":"white"},
{"source":"0","target":"2","weight":1,"color":"yellow"},
{"source":"0","target":"3","weight":1,"color":"white"},
{"source":"5","target":"7","weight":1,"color":"white"},
{"source":"5","target":"8","weight":1,"color":"yellow"},
{"source":"6","target":"9","weight":1,"color":"white"},
]
}

collectDict = defaultdict(list)
for obj in data["links"]:
    collectDict[obj["source"]].append(obj["target"])

print(dict(collectDict))

输出:

{'0': ['1', '2', '3'], '5': ['7', '8'], '6': ['9']}

编辑:这是另一种使用的方法itertools.groupby假设链接按来源排序(否则,只需在之前排序)

from itertools import groupby

collectDict = {k: [t["target"] for t in g] for k,g in groupby(data["links"], lambda obj: obj["source"])}

print(collectDict)

推荐阅读