[SOLVED] turning a Networkx graph into a dictionary

Issue

I generate a networkx graph with the following function:

import networkx as nx
import matplotlib.pyplot as plt
from itertools import combinations, groupby
import random
def gnp_random_connected_graph(n, p):
    """
    Generates a random undirected graph, similarly to an Erdős-Rényi 
    graph, but enforcing that the resulting graph is connected
    """
    edges = combinations(range(n), 2)
    G = nx.Graph()
    G.add_nodes_from(range(n))
    if p <= 0:
        return G
    if p >= 1:
        return nx.complete_graph(n, create_using=G)
    for _, node_edges in groupby(edges, key=lambda x: x[0]):
        node_edges = list(node_edges)
        random_edge = random.choice(node_edges)
        G.add_edge(*random_edge)
        for e in node_edges:
            if random.random() < p:
                G.add_edge(*e)
    return G

I would then like to color the created graph using the following function:

def coloring(adj, V):

    result = [-1] * V
    result[0] = 0
    available = [False] * V

    for y in range(0, V):
        for x in adj[y]:
            if y not in adj[x]:
                adj[x].append(y)

    for u in range(1, V):
        for i in adj[u]:
            if (result[i] != -1):
                available[result[i]] = True
        cr = 0
        while cr < V:
            if (available[cr] == False):
                break

            cr += 1

        result[u] = cr

        for i in adj[u]:
            if (result[i] != -1):
                available[result[i]] = False

    for u in range(V):
        print("Vertec", u, " --->  Color", result[u])

The problem is that I need to have the networkx graph as a dictionary to then insert it into coloring by doing the following:

coloring([node for node in g.values()], 5)

where g is the graph as dictionary
So how can I turn the networkx graph into a dictionary where the nodes are the keys and the nodes to which each node is connected is it’s associated value? Is there a way to do this without converting the networkx graph into a dictionary?

node: don’t mind the planarity of the graph, I’ll deal with it later on

Solution

Not sure if this is what you are looking for, but using a dictionary comprehension might help:

# this creates a dictionary where each node maps to list of neighbours
G_dict = {node: list(G[node]) for node in G}

Answered By – SultanOrazbayev

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.