社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

将Python字典中的JSON值累积为数组

obadul024 • 4 年前 • 772 次点击  

{ 
"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 都收齐了吗

这是我的密码

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"]

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

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/55681
 
772 次点击  
文章 [ 3 ]  |  最新文章 4 年前
Riccardo Bucco
Reply   •   1 楼
Riccardo Bucco    4 年前

import pandas as pd

result = [{"source": source, "neighbors": df["target"].tolist()}
          for source, df in pd.DataFrame(data["links"]).groupby("source")]
Michael H.
Reply   •   2 楼
Michael H.    4 年前
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"},
    ]
}

collected = []
for obj in data["links"]:
    source_matches = [item for item in collected if item["source"] == obj["source"]]
    if len(source_matches) == 0:
        source_match = {"source": obj["source"], "neighbour": [obj["target"]]}
        collected.append(source_match)
    elif len(source_matches) == 1:
        source_matches[0]["neighbour"].append(obj["target"])
    else:
        raise BaseException()

print(collected)  # [{'source': '0', 'neighbour': ['1', '2', '3']}, {'source': '5', 'neighbour': ['7', '8']}, {'source': '6', 'neighbour': ['9']}]

不是很优雅,但能胜任工作。

如果你真的不需要格式 {"source": 0, "neighbors": ["1","2","3"]} 我建议使用上面的解决方案 defaultdict . 如果需要这种格式,还可以从 默认听写 解决方案。

Adam.Er8
Reply   •   3 楼
Adam.Er8    4 年前

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