Understanding the syntax of dictionaries used for graph construction and how to manipulate them

47 views Asked by At

I have the following python dictionary representing a weighted graph

graph1 = {
    0: {1: 1, 2: 2},
    1: {0: 1, 2: 0, 3: 0, 4: 3},
    2: {0: 2, 1: 0, 5: 4},
    3: {1: 0, 4: 0},
    4: {1: 3, 3: 0, 5: 0},
    5: {2: 4, 4: 0, 6: 0},
    6: {5: 0},
}

I am trying to create an algorithem that allows for the generation of these graphs given number of nodes and edges. To understand how to create a graph from scratch I began by trying to add a single node to the graph above. I did the following:

graph1[7]={6:7}

This worked fine. Yet I failed to understand what the {6:7} is. Is it a dictionary within the dictionary? Is it a set ?

My aim is to be able to add random edges between a set of n nodes, so Im trying to figure out how to do the following.

graphSize=n
for i in range(graphSize)
    for j in range(rand(graphSize))
        Graph[i].add({"node that is not i","random wieght"})

This however is not possible cause dictionaries dont have an append or add function. Is there another way to do this?

1

There are 1 answers

0
Masklinn On

This worked fine. Yet I failed to understand what the {6:7} is. Is it a dictionary within the dictionary?

Yes. The syntax of dict literals in Python is {[key: value,]*}.

A set literal would not have the : (which separates keys and values).

This however is not possible cause dictionaries dont have an append or add function. Is there another way to do this?

The same way you add items to the Graph dict? Just assign to the index:

Graph[i][j] = whatever