Networkx报错:'MultiDegreeView'对象无values属性,如何使用字典values()?
解决AttributeError: 'MultiDegreeView' object has no attribute 'values'问题
这个错误是因为新版本的NetworkX中,nx.degree(G)返回的是MultiDegreeView(或DegreeView)视图对象,不再是传统字典,所以你不能直接调用values()方法来获取所有节点的度值。下面是具体的修复方案和优化后的代码:
核心问题修复
把原来获取度值的代码:
all_degrees = nx.degree(G).values()
替换成以下两种方式之一:
- 方式一(推荐,更高效):用列表推导式直接提取度值
all_degrees = [d for n, d in nx.degree(G)]
- 方式二:先把视图对象转成字典,再取values
all_degrees = list(dict(nx.degree(G)).values())
额外的代码优化
你的代码里还有一个matplotlib导入的小问题,规范写法应该是导入matplotlib.pyplot而不是整个matplotlib模块,这样代码更简洁:
把import matplotlib as plt改成import matplotlib.pyplot as plt,后续直接用plt.plot()和plt.show()即可。
修复后的完整代码
import networkx as nx import matplotlib.pyplot as plt def plot_deg_dist(G): # 提取所有节点的度值 all_degrees = [d for n, d in nx.degree(G)] # 获取唯一的度值 unique_degrees = list(set(all_degrees)) count_of_degrees = [] for deg in unique_degrees: count = all_degrees.count(deg) count_of_degrees.append(count) # 绘制度分布 plt.plot(unique_degrees, count_of_degrees) plt.xlabel("Degree") plt.ylabel("Number of Nodes") plt.title("Degree Distribution of Karate Club Network") plt.show() # 读取pajek文件 G = nx.read_pajek('karate.paj') # 可选:如果需要将MultiGraph转为普通Graph(避免多重边影响度计算) # G = nx.Graph(G) plot_deg_dist(G)
补充说明
nx.read_pajek()默认返回的是MultiGraph(支持多重边),如果你的网络不需要多重边,可以转成普通Graph(注释里的代码),这样度计算会更符合常规的无向图定义。- 我还给图表加了坐标轴标签和标题,让可视化结果更清晰。
内容的提问来源于stack exchange,提问作者Sahil Butola
相关产品推荐
相关产品推荐

