배열로 파이썬 사전에 축적 JSON 값

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.defaultdictA를 소스로부터 매핑, 목록 이 같은 목표의 :

(나는 여러 소스를 가지고 일부 데이터를 추가)

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)

추천

출처http://43.154.161.224:23101/article/api/json?id=23865&siteId=1