Joep Groentesoep
Joep Groentesoep

Reputation: 165

Add nodes with attributes to graph from a dictionary

So I have a dictionary and I want to input the keys as nodes into a graph. Then the values of the keys in the dictionary, they have to become attributes of the node. This is my code right now.

dictionary = {1:'a', 2:'b', 3:'c', 4:'d'}
G.nx.DiGraph()
G.add_nodes_from(dictionary.keys(), attribute = dictionary.values())
G.nodes[1]
>> {'attribute': dict_values(['a', 'b', 'c', 'd'])}

This is not the desired output. I actually only want 'a' as attribute from key 1. Desired output is:

G.nodes[1]
>> {'attribute': 'a'}

So the problem is in assigning my attributes. But how can I do this right?

Upvotes: 1

Views: 5480

Answers (2)

Joel
Joel

Reputation: 23827

To assign attributes to individual nodes, use G.add_edges_from(X) where X is a list (or other container) of tuples of the form (node, attribute_dict). So you need to create the attribute dictionary for each node. Let's use a list comprehension for that.

G.add_nodes_from([(node, {'attribute': attr}) for (node, attr) in dictionary.items()])

Upvotes: 3

silgon
silgon

Reputation: 7211

I haven't find an answer straight as a networkx function. However the following code works.

dictionary = {1:'a', 2:'b', 3:'c', 4:'d'}
G=nx.DiGraph()
G.add_nodes_from(dictionary.keys())
for key,n in G.nodes.items():
   n["attribute"]=dictionary[key]

Then you can see the attributes of each one.

G.nodes[1]
#result {'attribute': 'a'}

Upvotes: 0

Related Questions