obadul024:
私はこの形式を持つ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"]
すべてのヘルプは多くのことをいただければ幸いです。私はいくつかの基本的な考え方と私はここに行方不明だということを簡単な方法があると確信しています。助けてくれてありがとう。
adam.er8:
私が正しくあなたを理解していれば、あなたは使用することができ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)