Get startedGet started for free

Visualizing connectivity

Here, you're going to visualize how the connectivity of the top connected nodes changes over time. The list of top connected values, top_connected, from the previous exercise has been loaded.

Remember the defaultdict you used in Chapter 1? You'll use another defaultdict in this exercise! As Eric mentioned in the video, a defaultdict is preferred here as a regular Python dictionary would throw a KeyError if you try to get an item with a key that is not currently in the dictionary.

This exercise will make use of nested for loops. That is, you'll use one for loop inside another.

This exercise is part of the course

Intermediate Network Analysis in Python

View Course

Exercise instructions

  • Initialize a defaultdict of empty lists called connectivity.
  • Iterate over top_connected using a for loop, and in the body of this outer for loop, once again iterate over Gs. Inside this nested loop:
    • The keys of connectivity should be the nodes n in top_connected, and the values should be the list of connectivity scores. Therefore, you have to append len(list(G.neighbors(n))) to connectivity[n].
  • Iterate over connectivity using .items() and plot the connectivity of each node by passing in conn to plt.plot().

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Import necessary modules
import matplotlib.pyplot as plt
from collections import defaultdict

# Create a defaultdict in which the keys are nodes and the values are a list of connectivity scores over time
connectivity = ____
for n in ____:
    for g in ____:
        connectivity[____].____(len(____))

# Plot the connectivity for each node
fig = plt.figure() 
for n, conn in ____: 
    plt.plot(____, label=n) 
plt.legend()  
plt.show()
Edit and Run Code