3

Is there a way to pretty print a graph in NetworkX? For example:

>>> import networkx as nx >>> G = nx.Graph() >>> G.add_edge('Alan', 'Bob') >>> G.add_edge('Alan', 'Charles') >>> G.add_edge('Alan', 'Xavier') >>> G.add_edge('Charles', 'Xavier') >>> G.add_edge('Joan', 'Xavier') 

I would then like to see this graph as a json-like object, for example:

{ 'Alan': { 'Bob': {}, 'Charles': { 'Xavier': {} }, 'Xavier': {}, }, 'Joan': { 'Xavier': {} } } 

It doesn't have to be exactly like the above, but should give a good high-level data view of the graph (provided it's relatively small).

2
  • Can you provide and example of the printing you'd like to see? Commented Feb 5, 2020 at 22:50
  • @ScottBoston -- sure, I've updated the question with a better example. Commented Feb 5, 2020 at 22:52

1 Answer 1

10

In newtorkx version 2.3, there is a method nx.to_dict_of_dicts:

nx.to_dict_of_dicts(G) 

Output:

{'Alan': {'Bob': {}, 'Charles': {}, 'Xavier': {}}, 'Bob': {'Alan': {}}, 'Charles': {'Alan': {}, 'Xavier': {}}, 'Xavier': {'Alan': {}, 'Charles': {}, 'Joan': {}}, 'Joan': {'Xavier': {}}} 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.