Search code examples
pythonnetworkxtweepy

How to update this for NetworkX 2.0?


I am trying to write this but I just realized attr_dict is not supported in the new version of NetworkX as I am not getting the desired rows from the code below. Can someone tell me how to update this piece of code? Adding the row part is what's the issue as attr_dict is no longer supported.

if not this_user_id in G:
        G.add_node(this_user_id, attr_dict={
                'followers': row['followers'],
                'age': row['age'],
            })

This is the code in context

# Gather the data out of the row
#
    this_user_id = row['author']
    author = row['retweet_of']
    followers = row['followers']
    age = row['age']
    rtfollowers = row['rtfollowers']
    rtage = row['rtage']
#
# Is the sender of this tweet in our network?
#
    if not this_user_id in G:
        G.add_node(this_user_id, attr_dict={
                'followers': row['followers'],
                'age': row['age'],
            })
#
# If this is a retweet, is the original author a node?
#
    if author != "" and not author in G:
        G.add_node(author, attr_dict={
                'followers': row['rtfollowers'],
                'age': row['rtage'],
            })
#
# If this is a retweet, add an edge between the two nodes.
#
    if author != "":
        if G.has_edge(author, this_user_id):
            G[author][this_user_id]['weight'] += 1
        else:
            G.add_weighted_edges_from([(author, this_user_id, 1.0)])
 
nx.write_gexf(G, 'tweets1.gexf')

Solution

  • Now the add_node function accepts the node attributes directly as keyword arguments so you can reformulate the function to be:

    G.add_node(this_user_id, followers = row['followers'],age = row['age'])
    

    or if you have the attributes saved in a dict named my_attr_dict, you can say

    G.add_node(this_user_id,**my_attr_dict)