如果我理解正确,你可以使用
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)