I try to simulate a graph with dictionaries in python, in the following way:
G = {'a':{'b':3, 'c':4},
'b':{'a':3, 'c':5},
'c':{'a':4,'b':5},
}
Where G is a dictionary whose keys have a dictionary value associated with them. In turn, these keys are the adjacent nodes that have a respective weight associated as their value.
I have tried with this code however, I have not achieved my goal
def generarGrafo(num_nodos):
lista_nodos = []
lista_nodos_asociados = []
grafo = {}
for i in range(num_nodos):
nodo = raw_input(" ID Nodo %d:" %(i+1))
lista_nodos.append(nodo)
num_nodos_asociados = input(" Numero de nodos asociados a nodo '%s':" %(lista_nodos[i]))
lista_nodos_asociados.append([]) #Lista de listas para almacenar los nodos asociados a cada respectivo nodo i-esimo
for j in range(num_nodos_asociados):
nodo_asociado = raw_input(" ID nodo %d asociado:" %(j+1))
lista_nodos_asociados[i].append(nodo_asociado) #Se almacenan y muestran en el elemento i-esimo de la lista
peso_asociado = input(" Peso asociado (Arista(%s,%s) ): " %(lista_nodos[i],lista_nodos_asociados[i][j] ) )
grafo[lista_nodos[i]] = {}
grafo[lista_nodos[i]][lista_nodos_asociados[i][j]] = peso_asociado
return grafo
I get the following output: G = {'a':{'c':4}, 'b':{'c':5}, 'c':{'b':5}, }
For some reason it only places the second item in the list of associated nodes,
The problem is in the for loop that you use to generate the associated nodes, specifically in the line:
With it you create a new key/value pair in each iteration of the for, as a dictionary has a unique key, this deletes the previous one so that in the end only the last associated node that you enter will be saved. The solution is simple, remove this line from the for and put it before starting it:
This is the execution:
On the other hand, as it stands the function is very inefficient, the two lists are not needed and reading from them to create the dictionary is much slower than using the input values directly. You can simplify the code to make it more efficient, the following function does the same:
If the real function is different from the one you have published and if you use lists, what I recommend is that you create the dictionary with the input values and not obtaining the value of the corresponding list.