'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:
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.
Solution 1:[1]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | yut23 |