社区所有版块导航
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 • 5 年前 • 1369 次点击  

{ 
"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
 
1369 次点击  
文章 [ 3 ]  |  最新文章 5 年前