Buskruid
Buskruid

Reputation: 63

How to store multiple networkx graphs in one file?

What is the best way to store multiple networkx graphs in one file? This page shows various ways to store one graph, but not multiple. Is there a way to do this easily in e.g. a csv file? My goal is to store randomly generated graphs to do some analysis afterwards.

Thanks

Upvotes: 2

Views: 1024

Answers (1)

warped
warped

Reputation: 9481

A simple way would be to convert the graphs into a list of dictionaries, which can be pickled:

import pickle
import networkx as nx

# dummy graphs
G = nx.complete_graph(4)
H = nx.complete_graph(5)
I = nx.complete_graph(6)


def store_as_list_of_dicts(filename, *graphs):

    list_of_dicts = [nx.to_dict_of_dicts(graph) for graph in graphs]

    with open(filename, 'wb') as f:
        pickle.dump(list_of_dicts, f)
    

def load_list_of_dicts(filename, create_using=nx.Graph):
    
    with open(filename, 'rb') as f:
        list_of_dicts = pickle.load(f)
    
    graphs = [create_using(graph) for graph in list_of_dicts]
    
    return graphs


store_as_list_of_dicts('test.pkl', G,H,I)

graphs = load_list_of_dicts('test.pkl')

alternative graph constructors:

graphs = load_list_of_dicts('test.pkl', create_using=nx.MultiDiGraph)

Upvotes: 2

Related Questions