Zubo
Zubo

Reputation: 1593

Access GraphML attributes after importing as NetworkX graph

I have a graph, stored in graphml format, which includes a bunch of attributes, like

<key attr.name="label" attr.type="string" for="node" id="d0"/>

and in a node

  <data key="d0">this node's label</data>

I've imported this file using nx.read_graphml('mygraph.graphml'). I can visualize the graph (using nx.draw_networkx(imported_graph)), and I can export it again (using nx.write_graphml(imported_graph, 'exported.txt', encoding='utf-8', prettyprint=True)), and I see that all the attributes are kept.

I'd like to work with nodes by accessing them based on their attributes. So I check what attributes all the nodes have like so:

for i in imported_graph.__iter__():
    print(i)
    print(nx.get_node_attributes(imported_graph, i))

I get

0
{}
1
{}

and so on, so no node has any attributes? What am I doing wrong?

Upvotes: 2

Views: 665

Answers (1)

michaelg
michaelg

Reputation: 954

How to iterate on networkx nodes ?

create nodes

G = nx.Graph()
_ = [G.add_node(i, a=random.randint(1,10), b=random.randint(1,10), c=random.randint(1,10)) for i in range(20)]

iterate

for node in G.nodes(data=True):
    print(node)

[out]:

(0, {'a': 5, 'b': 6, 'c': 10})
(1, {'a': 3, 'b': 4, 'c': 9})
(2, {'a': 4, 'b': 3, 'c': 4})
(3, {'a': 1, 'b': 5, 'c': 2})
(4, {'a': 10, 'b': 1, 'c': 6})
(5, {'a': 10, 'b': 10, 'c': 5})
(6, {'a': 8, 'b': 9, 'c': 9})
(7, {'a': 9, 'b': 7, 'c': 5})
(8, {'a': 1, 'b': 2, 'c': 10})
(9, {'a': 8, 'b': 6, 'c': 9})
(10, {'a': 2, 'b': 4, 'c': 8})
(11, {'a': 5, 'b': 8, 'c': 3})
(12, {'a': 1, 'b': 3, 'c': 8})
(13, {'a': 3, 'b': 8, 'c': 7})
(14, {'a': 5, 'b': 5, 'c': 7})
(15, {'a': 8, 'b': 6, 'c': 5})
(16, {'a': 2, 'b': 6, 'c': 5})
(17, {'a': 6, 'b': 8, 'c': 2})
(18, {'a': 10, 'b': 6, 'c': 10})
(19, {'a': 2, 'b': 9, 'c': 6})

Upvotes: 1

Related Questions