简体   繁体   中英

Reading from a .txt file and creating a nested dictionary python

I'm new to python and need some help regarding dictionaries.I have a text file

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

which represents source and destiantion nodes in a graph with the cost. I want to read the file and create a dictionary of the format

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

and so on for every node with every adjacent node and cost between them.

I think that the following simple code should work for you.

# 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)

Where graph is the final dictionary that you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM