簡體   English   中英

從 .txt 文件讀取並創建嵌套字典 python

[英]Reading from a .txt file and creating a nested dictionary python

我是 python 新手,需要一些有關詞典的幫助。我有一個文本文件

1;2;0.0008131  
1;714;0.0001097  
714;715;0.0016285  
715;796;0.0014631  
... 

它用成本表示圖中的源節點和目標節點。 我想讀取文件並創建一個格式的字典

{'1': {'2': 0.0008131, '714': 0.0001097},
        '2': {'1': 0.0008131, '523': 0.0001097},
        '3': {'252': 0.0001052, '613':0.0002097},

對每個節點和每個相鄰節點以及它們之間的成本,依此類推。

我認為以下簡單的代碼應該適合您。

# Open your text file
f = open('file.dat')

# Create empty dictionary 
graph = {}

for line in f:
    x = line.rstrip().split(";")
    if not x[0] in graph:
        graph[x[0]] = {x[1] : x[2]}
    else:
        graph[x[0]][x[1]] = x[2]

    if not x[1] in graph:
        graph[x[1]] = {x[0] : x[2]}
    else:
        graph[x[1]][x[0]] = x[2]

print(graph)

其中graph是您想要的最終字典。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM