python - Converting a graph into dictionary form
问题描述
I am currently writing a program to model Dijkstra's algorithm, however I am having some trouble the graph in its current form below:
G = [['a', 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h', 'i', 'j'],
[({'a', 'b'}, 4), ({'a', 'c'}, 6), ({'a', 'd'}, 8), ({'b', 'e'}, 1) ,
({'b', 'f'}, 9), ({'c', 'f'}, 2), ({'d', 'g'}, 7), ({'d', 'h'}, 1) ,
({'e', 'i'}, 2), ({'e', 'j'}, 7), ({'g', 'h'}, 2), ({'i', 'j'}, 4)]]
I want to get the graph in the form such as the one below
{ 'a': {'b': 4, 'c': 6, 'd': 8},
'b': {'a': 4, 'e': 1, 'f': 9}, etc
Would this be possible?
解决方案
You can use collections.defaultdict
for this.
Code:
from collections import defaultdict
G = [['a', 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h', 'i', 'j'],
[({'a', 'b'}, 4), ({'a', 'c'}, 6), ({'a', 'd'}, 8), ({'b', 'e'}, 1) ,
({'b', 'f'}, 9), ({'c', 'f'}, 2), ({'d', 'g'}, 7), ({'d', 'h'}, 1) ,
({'e', 'i'}, 2), ({'e', 'j'}, 7), ({'g', 'h'}, 2), ({'i', 'j'}, 4)]]
result = defaultdict(dict)
for edge in G[1]:
v1, v2 = edge[0]
result[v1][v2] = edge[1]
result[v2][v1] = edge[1]
print(result)
Output:
defaultdict(<class 'dict'>,
{'a': {'b': 4, 'c': 6, 'd': 8},
'b': {'a': 4, 'e': 1, 'f': 9},
'c': {'a': 6, 'f': 2},
'd': {'a': 8, 'g': 7, 'h': 1},
'e': {'b': 1, 'i': 2, 'j': 7},
'f': {'b': 9, 'c': 2},
'g': {'d': 7, 'h': 2},
'h': {'d': 1, 'g': 2},
'i': {'e': 2, 'j': 4},
'j': {'e': 7, 'i': 4}})
推荐阅读
- python - SKLearn 多分类,无需预先了解 Python 中的分类
- r - 在加权无向图中测量社区之间的距离
- vba - 公式计算出值后,如何将公式更改为静态值?
- java - 在spring boot中创建一个REST API来上传Multipart文件数据
- macos - 什么是 CGEvent 中的像素单元(CGScrollEventUnit.pixel)?
- postgresql - Heroku Postgres 在排序时忽略下划线
- amazon-web-services - 我正在尝试将 csv 文件导入 HDFS。我收到一个错误,指出:-cp:没有足够的参数预期 2 但得到 1?
- sql - 需要帮助在 Oracle 中创建正确的联接
- youtube - 如何获取已删除的 YouTube 视频和订阅者?
- vue.js - 如何在d3中制作多系列条形图?