python字典怎么做图
时间: 2023-12-02 16:30:07 浏览: 54
Python 字典可以通过使用第三方库 `networkx` 和 `matplotlib` 来进行图形化展示。
下面是一个简单的示例代码:
```python
import networkx as nx
import matplotlib.pyplot as plt
# 创建字典
my_dict = {
'A': {'B': 1, 'C': 2},
'B': {'C': 3, 'D': 4},
'C': {'D': 5},
'D': {}
}
# 创建有向图
G = nx.DiGraph()
# 添加节点
for node in my_dict.keys():
G.add_node(node)
# 添加边
for node, edges in my_dict.items():
for edge, weight in edges.items():
G.add_edge(node, edge, weight=weight)
# 绘制图形
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_edges(G, pos)
nx.draw_networkx_edge_labels(G, pos, edge_labels=nx.get_edge_attributes(G, 'weight'))
nx.draw_networkx_labels(G, pos)
plt.show()
```
运行以上代码,将会生成一个类似于下面的图形:
![python_dict_graph](https://img-blog.csdn.net/20180313143747153)
阅读全文