将具有重叠键的嵌套字典转换为 NetworkX

问题描述 投票:0回答:1

据我所知,我这里真的一团糟。我的目标是一个有向且加权的网络。我面临的主要问题是,我尝试转换为加权边缘的输出来自“for”循环,并且无论我做什么,我都倾向于获得循环的第一个或最后一个输出。

它看起来像这样:

import networkx as nx
import matplotlib.pyplot as plt
G2 = nx.DiGraph()
compiledDict = {'A': ['A_1', 'A_2', 'A_3', 'A_4', 'A_5', 'A_6'], 'B': ['B_1', 'B_2', 'B_3', 'B_2', 'B_4', 'B_5', 'B_1', 'B_6', 'B_4']

for x in compiledDict:
    dNotFinalAfterAll={}
    forthelasttime=compiledDict.get(x)
    for item in forthelasttime:
        dNotFinalAfterAll[x]={item:forthelasttime.count(item)}
        print(dNotFinalAfterAll)

输出的简化版本如下,每一行都是 for 循环的一个输出。目标是让它的其中 {A:{B:C}} 是 A 是传出节点,B 是传入节点,C 是权重:

{'B': {'B_1': 2}}
{'B': {'B_2': 2}}
{'B': {'B_3': 1}}
{'B': {'B_2': 2}}

如果有一种方法可以让像 {'B': {'B_2': 2}} 这样的重复项只出现一次,那就太好了,但只要它有效,它就可以变得很丑陋。需要概念证明而不是持续的过程。 我想把它做成一个数据框。它没有发生。我得到的最接近的是将其放在不同的地方:

G2 = nx.DiGraph((k, v, {'weight': weight}) for k, vs in dNotFinalAfterAll.items() for v, weight in vs.items())
for s, t, w in G2.edges(data=True):
    print(s,t,w)
    G2.add_edge(s,t,weight = w)

无论我是否将其放入 for 循环中,通常都会输出此内容:

Z Z_3 {'weight': 1}
dictionary jupyter-notebook nested networkx
1个回答
0
投票

假设您想从输入字典构建加权有向图,您可以利用

collections.Counter
:

from collections import Counter
import networkx as nx

compiledDict = {'A': ['A_1', 'A_2', 'A_3', 'A_4', 'A_5', 'A_6'],
                'B': ['B_1', 'B_2', 'B_3', 'B_2', 'B_4', 'B_5', 'B_1', 'B_6', 'B_4']}

G2 = nx.DiGraph()

for k1, l in compiledDict.items():
    for k2, w in Counter(l).items():
        G2.add_edge(k1, k2, weight=w)
© www.soinside.com 2019 - 2024. All rights reserved.