I want to access and store nodes of networkx graph and then do further processing on it. I have following code:
for node in vis:
for a,b in G[node]:
print a,b
This code gives following Error : Traceback (most recent call last):[1]
File "C:\Users\Mrinal\workspace\algo_asgn1\prims.py", line 29, in <module>
for a,b in G[node]:
TypeError: 'int' object is not iterable
whereas when i write:
for node in vis:
print G[node]
I get following output which I suppose is a dictionary with key as destination node and weight of the connection as value.
{2: {'weight': 5}, 3: {'weight': 2}, 4: {'weight': 2}}
{2: {'weight': 5}, 3: {'weight': 2}, 4: {'weight': 2}}
{2: {'weight': 5}, 3: {'weight': 2}, 4: {'weight': 2}}
{2: {'weight': 5}, 3: {'weight': 2}, 4: {'weight': 2}}
{2: {'weight': 5}, 3: {'weight': 2}, 4: {'weight': 2}}
My graph has following data:
1 2 5
1 3 2
2 3 4
2 4 6
1 4 2
What mistake am I doing over here? Can someone please suggest me changes. Thanks
G[node]
is a dictionary. Iterating over a dictionary gives you the keys of that dictionary , which in this case are the integers 2,3,4
. Thus, if you run this snippet you get the following output:
>>> for a in {2: {'weight': 5}, 3: {'weight': 2}, 4: {'weight': 2}}:
... print a
...
2
3
4
The problem you're having stems from the fact that you are trying to iterate over two variables -- for a, b in x
-- where x
is an integer and thus can't split into two separate variables. Instead, just use a single variable to get the node, eg
>>> node = {2: {'weight': 5}, 3: {'weight': 2}, 4: {'weight': 2}}
>>> for a in node:
... print a, node[a]
...
2 {'weight': 5}
3 {'weight': 2}
4 {'weight': 2}
I figured out what I was doing wrong here that i did not use .iteritems()
for node in vis:
for a,b in G[node].iteritems():
print a,b
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.