Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - how to create dictionary of dictionary in loop

I am trying to generate a graph of cities from a file. Each readline() I am getting three values, a, b, and c. a and b are strings, names of cities, and c is an int, the path cost between a and b. How can I store a,b,c so that I get something like

graph = {
          'a1': {'b1': c1, 'b1': 5, 'a2': c2},
          'a2': {'a1': c2},
          'b1': {'a1': c1},
        }

Here is part of my code:

dict = dict()   #dictionary for storing values
while (True):
    new_path = file.readline()
    if new_path == "":
        break
    new_path = new_path.rstrip().split(", ")
    a = new_path[0][2:len(new_path[0]) - 1] #start town
    b = new_path[1][1:len(new_path[1]) - 1] #end town
    c = new_path[2][0:len(new_path[2]) - 1] #path cost
    print(a+" "+b+" "+c)   #this prints Arlington Chelmsford 4

....... Since I don't know if the key is already in the dictionary, I have tried adding the key with empty value if key is not in dict.keys(), but then update() will function weirdly and give me some sort of list. I am new to python so please explain to me how to create such a graph that doesn't include any [] symbol in. Thanks a million!!

the final result I want would be something like this:

{'Arlington': {'Chelmsford': 4, 'Berkshire': 10}, 'Chelmsford': {'Arlington': 4, 'Berkshire': 5}, 'Berkshire': {'Arlington': 10, 'Chelmsford': 5}}

like image 697
Biying Zhang Avatar asked Oct 16 '22 12:10

Biying Zhang


1 Answers

You can use the following loop that sets the graph dict in both directions:

graph = {}
for line in file:
    a, b, c = line.rstrip().split(', ')
    graph.setdefault(a, {})[b] = c
    graph.setdefault(b, {})[a] = c

so that given file content:

Arlington, Chelmsford, 4
Arlington, Berkshire, 10
Chelmsford, Berkshire, 5

graph would become:

{'Arlington': {'Chelmsford': '4', 'Berkshire': '10'}, 'Chelmsford': {'Arlington': '4', 'Berkshire': '5'}, 'Berkshire': {'Arlington': '10', 'Chelmsford': '5'}}

like image 187
blhsing Avatar answered Oct 21 '22 09:10

blhsing