Creating Weighted Directed Graph in Python based on User Input
<p>I need to create something like this to represent a directed weighted graph based on user input - </p>

<pre><code>graph = {
          'a': {'b': 1, 'c':  4},
          'b': {'c':  3, 'd':  2, 'e':  2},
          'c': {},
          'd': {'b':  1, 'c':  5},
          'e': {'d': -2}
        }
</code></pre>

<p>So far,</p>

<pre><code>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)
</code></pre>

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

<pre><code>for i in graph:
    graph[i] = edges
</code></pre>

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

<pre><code>for i in graph:
    graph[i] = edges.copy()
</code></pre>

python python-3.x dictionary graph-theory