Python 创建嵌套字典

Python 创建嵌套字典,python,networkx,Python,Networkx,我是python新手,每天都在学习和计算新事物。我有一个文本文件,它的结构如下 2011 1 2 4043.428261 2011 1 3 1129.99031 . . . . . . . . 2012 1 4 2610.262872 2012 1 5 1526.420342 . . . . . . . . 2013 1 6 497.5094923

我是python新手,每天都在学习和计算新事物。我有一个文本文件,它的结构如下

2011    1   2   4043.428261
2011    1   3   1129.99031
.       .   .   .
.       .   .   .
2012    1   4   2610.262872
2012    1   5   1526.420342
.       .   .   .
.       .   .   .
2013    1   6   497.5094923
2013    1   7   6666.273778
.       .   .   .
.       .   .   .
2014    1   8   502.258575
2014    1   9   1134.696447
我想创建一个嵌套字典,以年度定向网络图的形式捕获这些信息。fileIn[0]年,fileIn[1]为源节点,fileIn[2]为目标节点,fileIn[3]为权重。defaultdict将用于捕获网络的其他属性。 目前,我正在运行下面的代码,这给了我一个空图。另外,当我运行短代码时,我得到一个错误networkx没有属性有向图。 我们将非常感谢您的帮助。提前谢谢

import networkx as nx
from collections import defaultdict 
G = {}
fileIn = open("Data3.txt", 'r').readlines()
for line in fileIn:
    line = line.strip('\n')
    year, u, v, amount = line.split('\t')
    print(year, u, v, amount)
    print(type(u), type(v), type(amount))
    year_id = ('2011', '2012', '2013', '2014')
    #print(year_id)

    year = year_id
    print(G)
    if year not in G.keys():
        G[year] = nx.Digraph(total_lends = 0)

我相信这应该满足你的要求:

import networkx as nx
import networkx.drawing
from collections import defaultdict
import matplotlib.pyplot as plt

G = nx.Graph()
graphs = {}
year_id = ('2011', '2012', '2013', '2014')

fileIn = open("Data3.txt", 'r').readlines()
for line in fileIn:
    line = line.strip('\n')
    year, u, v, amount = [n for n in ' '.join(line.split("\t")).split(' ') if n]
    this_year_id = year = year_id.index(year)

    if this_year_id not in graphs.keys():
        graphs[this_year_id] = nx.DiGraph(G)

    graphs[this_year_id].add_weighted_edges_from([(u, v, amount)])

for i, graph in graphs.items():
    ax = plt.subplot(221 + i)
    ax.set_title(str(2011+i))
    nx.draw(graphs[0], with_labels=True, font_weight='bold')

plt.show()
正如@sim指出的,您想要的是
有向图
,而不是
有向图
,这正是导致您出错的原因


原始代码的另一个问题是,在循环中,
year\u id
元组被分配给
year
,因此
G
拥有的唯一键是
('2011','2012','2013','2014')
。边也从来没有真正放在有向图上。

它被称为
有向图
而不是
有向图
。谢谢你为我指出了正确的方向,代码运行良好