Specifying a weight on edges
Weights can be added to edges in a graph, typically indicating the "strength" of an edge. In NetworkX, the weight is indicated by the 'weight' key in the metadata dictionary.
Before attempting the exercise, use the IPython Shell to access the dictionary metadata of T and explore it, for instance by running the commands T.edges[1, 10] and then T.edges[10, 1]. Note how there's only one field, and now you're going to add another field, called 'weight'.
This exercise is part of the course
Introduction to Network Analysis in Python
Exercise instructions
- Set the
'weight'attribute of the edge between node1and10ofTto be equal to2. Refer to the following template to set an attribute of an edge:network_name.edges[node1, node2]['attribute'] = value. Here, the'attribute'is'weight'. - Set the weight of every edge involving node
293to be equal to1.1. To do this:- Using a
forloop, iterate over all the edges ofT, including themetadata. - If
293is involved in the list of nodes[u, v]:- Set the weight of the edge between
uandvto be1.1.
- Set the weight of the edge between
- Using a
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Set the weight of the edge
____ = 2
# Iterate over all the edges (with metadata)
for u, v, d in ____:
# Check if node 293 is involved
if 293 in ____:
# Set the weight to 1.1
____ = 1.1