Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to save a 'pos dictionary' type of object? (NetworkX)

I am using the networkx as nx. After creating a graph object (G), I use the data = nx.spring_layout(G) method to generate a dictionary (pos). Generating this pos object is very time-consuming and I want to save it as a file, so I don’t have to rerun it all whenever I want to work with this dataset.
This is what it looks like so far:

G = nx.Graph()
G.add_edges_from(tuples)
data = nx.spring_layout(G)

If I run type(data), I receive ‘dict’. If I run type(G), I receive ‘networkx.classes.graph.Graph’.

Since it is a ‘dict’ object, these are some solutions I found online that I tried and didn’t work:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1. Save it as a .csv file

import csv

w = csv.writer(open("output.csv", "w"))

for key, val in data.items():
    w.writerow([key, val])

2. Save as JSON file

import json
json = json.dumps(data)


f = open("data.json","w")

f.write(json)

f.close()

3. Save as a .txt file

f = open("data.txt","w")

f.write( str(data) )

f.close()

Hopefully I made it clear that (i) I don’t know which type of file is the best one to save this sort of object; that (ii) I don’t know how to save it in any way; and (iii) that, naturally, I don’t know how to properly load this file as ‘pos dict’ object once it is saved in my directory.

For reference, nx.spring_layout(G) returns:
"pos: dict
A dictionary of positions keyed by node.", as described in the documentation.

Thanks in advance for the help!

>Solution :

Probably the simplest way to store a python object for later use is to use the pickle module:

import pickle

# save data
with open('positions.pickle', 'wb') as f:
    pickle.dump(data, f)

# load data
with open('positions.pickle', 'rb') as f:
    data = pickle.load(f)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading