1

I need to create something like this to represent a directed weighted graph based on user input -

graph = {
          'a': {'b': 1, 'c':  4},
          'b': {'c':  3, 'd':  2, 'e':  2},
          'c': {},
          'd': {'b':  1, 'c':  5},
          'e': {'d': -2}
        }

So far,

import pprint

graph = {}
values = {}
v = int(input("Enter number of vertices: "))

print("Enter vertices(keys) : ")
for i in range(v):
    graph.setdefault(input())

edges = {}
for x in graph:
    edges.setdefault(x)

for i in graph:
    graph[i] = edges

print("Enter weights: ")
for i in graph:
    print(i)
    for j in graph[i]:
        var = input()
        graph[i][j] = var

pprint.pprint(graph)

I tried but for some reason, it is replacing the previously read weights with last read weights. Any solutions?

Abhishek
  • 95
  • 1
  • 1
  • 8

2 Answers2

1
for i in graph:
    graph[i] = edges

You're assigning the same dict (edges) to each key of graph. Therefore, when you assign a value to any of them, you're assigning that value to all of them. It looks like what you actually want is copies of edges. In this case, since you haven't assigned any mutable values to edges, a shallow copy is sufficient:

for i in graph:
    graph[i] = edges.copy()
glibdud
  • 7,550
  • 4
  • 27
  • 37
  • It worked! Thanks. However while taking input i.e. taking weights for edges, the order of the keys is random. It will sometimes ask for any vertex & not the one which was inserted first & then second & so on. Any suggestions? – Abhishek Oct 14 '16 at 12:50
  • 1
    @Abhishek dicts have no concept of order. If you need to display items in a particular order, you'll need to sort them yourself. Or you can explore [collections.OrderedDict](https://docs.python.org/3.5/library/collections.html#collections.OrderedDict). – glibdud Oct 14 '16 at 12:56
0

Do you have an indentation error?

Instead of

for i in graph:
    print(i)
for j in graph[i]:
    var = input()
    graph[i][j] = var

You maybe intended to write

for i in graph:
    print(i)
    for j in graph[i]:
        var = input()
        graph[i][j] = var

?

mondano
  • 827
  • 10
  • 29