How to create a dictionary with multiple values inside another dictionary in python
<p>I  want to simulate a graph using dictionaries in Python.</p>

<pre><code>G = {'a':{'b':3, 'c':4},
     'b':{'a':3, 'c':5},
     'c':{'a':4,'b':5},
   }
</code></pre>

<p>G is a dictionary where each value is a dictionary which represents adjacent nodes with its weight.</p>

<p>I have the following code:</p>

<pre><code>def Graph(nodes):   
        list_nodes = []
        list_adjacent_nodes = []
        graph = {}

    for i in range(nodes):
        node = raw_input(" ID Node %d:" %(i+1))
        list_nodes.append(node)        
        num_adjacent_nodes = input("  Num adjacent nodes '%s':" %(list_nodes[i]))
        list_adjacent_nodes.append([])    
        for j in range(num_adjacent_nodes):
            adjacent_node = raw_input("   ID adjacent nodes %d:" %(j+1))
              list_adjacent_nodes.append[i].append(adjacent_node)  
            weight = input(" Wight (Nodes(%s,%s) ): " %(list_nodes[i],list_adjacent_nodes[i][j] ) )
            graph[list_nodes[i]] = {}
            graph[lista_nodes[i]][list_adjacent_nodes[i][j]] = weight
  return graph
</code></pre>

<p>However, I get the following result:</p>

<pre><code>G = {'a':{'c':4}, 'b':{'c':5}, 'c':{'b':5}, }
</code></pre>

<p>Where have I gone wrong and how can I return my desired output?</p>

<p>You overwrite the "inner" dictionary in each iteration of the loop with an empty dictionary. You should do so only if it's missing:</p>

<pre><code>if not graph[list_nodes[i]]: # Here!
    graph[list_nodes[i]] = {}
graph[list_nodes[i]][list_adjacent_nodes[i][j]] = weight
</code></pre>

python dictionary