Using nested dictionaries to store user defined graph
<p>I am trying to get the user to enter a graph manually as opposed to using it 'pre-existing' in the code, for use in my Dijkstra's Algorithm. </p>

<p>I have done this but would like some feedback on its implementation and user friendliness. In addition is there a more efficient way of entering a graph into a nested dictionary ? If so how ?.</p>

<p>Key points about code</p>

<ul>
<li>Data must be stored using nested dictionaries </li>
<li>A loop would be a zero e.g b-b is 0 not left blank, but this only occurs if a loop is present in user graph otherwise its ignored.</li>
<li>Ideally I would not like to use anything inside existing libraries before coding it myself to get a better understanding of what is happening</li>
</ul>

<p>Many Thanks. 
Edit: repeat requirement no longer needed.</p>

<pre><code>{'A': {'C': 1, 'B': 5}, 'D': {}, 'B': {'D': 2}, 'C': {'D': 9}}
</code></pre>

<p>^ Desired output for nodes also current output.</p>

<pre><code>nodes = {}


def add_node():
    entered_graph = False
    while not entered_graph:
        source_node = input("Enter a source node: ")
        num_neighbours = int(input("Enter how many neighbours this node has"
                                   "including previously entered nodes: "))
        nodes[source_node] = {}
        for neighbour in range(num_neighbours):
            neighbour = input("Enter neighbor node: ")
            distance = int(input("Enter distance from source node to this neighbor node: "))
            nodes[source_node][neighbour] = distance
        end_loop = input("Enter y to finish graph entry: ")
        end_loop = end_loop.lower()
        if end_loop == "y":
            entered_graph = True

add_node()
print(nodes)
</code></pre>

<p><a href="https://www.khanacademy.org/computing/computer-science/algorithms/graph-representation/a/representing-graphs" rel="nofollow">Khanacademy</a> has a pretty good page on different ways to represent graphs.</p>

<p>For an undirected graph (a => b and b => a) I would personally look at using an edge list. It can be sorted to improve lookup efficiency, and it is more memory efficient than other methods such as an adjacency table</p>

python dictionary