Node attribute question

27 views
Skip to first unread message

jcs

unread,
Dec 18, 2009, 7:09:19 PM12/18/09
to networkx-discuss
I'm trying to set node attributes using the follow code:

gr = nx.DiGraph()
....
k = node_id
gr.node[k]['strahler'] = number
....

This code loops through all nodes to set the attribute 'strahler',
when it is finished, however, all of the nodes have attr 'strahler'
set to whatever the last [k]['strahler'] assignment was.

It's like I can't set the nodes attributes individually.....

can anyone help?!?
thanks!

Aric Hagberg

unread,
Dec 18, 2009, 7:48:59 PM12/18/09
to networkx...@googlegroups.com

Hard to tell without the whole code.
Does this work for you?

------
import networkx as nx
print nx.__version__ # 1.0.dev1495
D=nx.DiGraph()
D.add_path(range(4))
for n in D:
D.node[n]['a']=3-n
print D.nodes(data=True) # [(0, {'a': 3}), (1, {'a': 2}), (2, {'a':
1}), (3, {'a': 0})]
-------

Aric

Christopher Ellison

unread,
Dec 18, 2009, 8:00:12 PM12/18/09
to networkx...@googlegroups.com
jcs wrote the following on 12/18/2009 04:09 PM:
> I'm trying to set node attributes using the follow code:
>
> gr = nx.DiGraph()
> ....
> k = node_id
> gr.node[k]['strahler'] = number
> ....
>
> This code loops through all nodes to set the attribute 'strahler',
> when it is finished, however, all of the nodes have attr 'strahler'
> set to whatever the last [k]['strahler'] assignment was.
>

Is this *exactly* what you are doing? That is, is "number" truly a raw
float? I wonder if "number" is actually a reference to a variable and
in your assignments, you are making all values point to the same
"number". If so, this is not a NetworkX issue. For example, compare
the output of the following:

>>> x = {}
>>> n = 0
>>> for i in range(10):
... n += i
... x[i] = n
...
>>> print x
{0: 0, 1: 1, 2: 3, 3: 6, 4: 10, 5: 15, 6: 21, 7: 28, 8: 36, 9: 45}

>>> x = {}
>>> n = []
>>> for i in range(10):
... n[0] += i
... x[i] = n
...
>>> print x
{0: [45],
1: [45],
2: [45],
3: [45],
4: [45],
5: [45],
6: [45],
7: [45],
8: [45],
9: [45]}

A complete, minimal example demonstrating the problem would be helpful.

Hope that helps,
Chris

Reply all
Reply to author
Forward
0 new messages