python - 将 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"]
任何帮助将不胜感激。我确信这里缺少一些基本概念和一种简单的方法。谢谢您的帮助。
解决方案
如果我理解正确,您可以使用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)
推荐阅读
- javascript - 如何每 5 个值插入一个换行符?
- postgresql - 在 Postgres 11.6 中从循环开始时选择事件
- docker - Asp.Net Core docker-compose https 自签名证书问题
- oauth-2.0 - 尝试检索 Oauth access_token 时出现 AADSTS50146 错误
- python - 使用 f2py 在 python 中的 Fortran 基本函数
- pdf - 在 Google Apps 脚本中创建多个 PDF 时出错
- reactjs - 错误:当我在 React 中尝试使用 Jest 进行测试时,无法找到带有文本的元素
- c# - Interlocked.CompareExchange 单线程等效代码
- vue.js - 自动完成字符突出显示
- python - 如何在 python pandas 数据透视表中找到总共只有一列?