[英]Convert text file with 3 columns into nested dict of dict in Python
我有一個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]
您可以讀入數據並按第一個值(FromNodeId)進行分組:
import itertools, re
file_data = [[*a, int(b)] for *a, b in [re.split('\s+', i.strip('\n')) for i in open('filename.txt')]]
last_results = {a:dict(i[1:] for i in b) for a, b in itertools.groupby(sorted(file_data, key=lambda x:x[0]), key=lambda x:x[0])}
輸出:
{'A': {'B': 5, 'D': 3, 'E': 12, 'F': 5}, 'B': {'A': 5, 'D': 1, 'G': 2}, 'C': {'G': 2, 'E': 1, 'F': 16}, 'D': {'B': 1, 'G': 1, 'E': 1, 'A': 3}, 'E': {'A': 12, 'D': 1, 'C': 1, 'F': 2}, 'F': {'A': 5, 'E': 2, 'C': 16}, 'G': {'B': 2, 'D': 1, 'C': 2}}
您評論原始代碼為:
g = nx.read_edgelist('sample2.txt', nodetype=str, data=(('Weight', int),), create_using=nx.DiGraph())
graph = nx.to_dict_of_dicts(g,edge_data = None)
返回如下內容:
{'A': {'B': {'Weight': 5},
'D': {'Weight': 3},
'E': {'Weight': 12},
'F': {'Weight': 5}},
'B': {'A': {'Weight': 5}, 'D': {'Weight': 1}, 'G': {'Weight': 2}},
'C': {'E': {'Weight': 1}, 'F': {'Weight': 16}, 'G': {'Weight': 2}},
'D': {'A': {'Weight': 3},
'B': {'Weight': 1},
'E': {'Weight': 1},
'G': {'Weight': 1}},
'E': {'A': {'Weight': 12},
'C': {'Weight': 1},
'D': {'Weight': 1},
'F': {'Weight': 2}},
'F': {'A': {'Weight': 5}, 'C': {'Weight': 16}, 'E': {'Weight': 2}},
'G': {'B': {'Weight': 2}, 'C': {'Weight': 2}, 'D': {'Weight': 1}}}
這很接近,您可以使用字典理解手動清除它:
clean_graph = {a: {b: edge['Weight'] for b, edge in a_vals.items()} for a, a_vals in graph.items()}
產生:
{'A': {'B': 5, 'D': 3, 'E': 12, 'F': 5},
'B': {'A': 5, 'D': 1, 'G': 2},
'C': {'E': 1, 'F': 16, 'G': 2},
'D': {'A': 3, 'B': 1, 'E': 1, 'G': 1},
'E': {'A': 12, 'C': 1, 'D': 1, 'F': 2},
'F': {'A': 5, 'C': 16, 'E': 2},
'G': {'B': 2, 'C': 2, 'D': 1}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.