我有一个txt文件如下:
#FromNodeId ToNodeId Weight
B A 5
B D 1
B G 2
A B 5
A D 3
A E 12
A F 5
D B 1
D G 1
D E 1
D A 3
G B 2
G D 1
G C 2
C G 2
C E 1
C F 16
E A 12
E D 1
E C 1
E F 2
F A 5
F E 2
F C 16
我想将其转换为一个图表,作为 python 中的字典的字典,如下所示:
graph = {
'B': {'A': 5, 'D': 1, 'G': 2},
'A': {'B': 5, 'D': 3, 'E': 12, 'F' :5},
'D': {'B': 1, 'G': 1, 'E': 1, 'A': 3},
'G': {'B': 2, 'D': 1, 'C': 2},
'C': {'G': 2, 'E': 1, 'F': 16},
'E': {'A': 12, 'D': 1, 'C': 1, 'F': 2},
'F': {'A': 5, 'E': 2, 'C': 16}}
我该怎么做?
最佳答案
import csv, collections
tree = collections.defaultdict(dict)
with open(filepath) as fd:
reader = csv.reader(fd, delimiter = ' ', skipinitialspace = True)
for row in reader:
tree[row[0]][row[1]] = row[2]
关于python - 将 3 列的文本文件转换为 Python 中 dict 的嵌套 dict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49544742/