社区所有版块导航
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学习  »  Michael H.  »  全部回复
回复总数  1
5 年前
回复了 Michael H. 创建的主题 » 将Python字典中的JSON值累积为数组
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 . 如果需要这种格式,还可以从 默认听写 解决方案。