1. Learn
  2. /
  3. Courses
  4. /
  5. Intermediate Network Analysis in Python

Connected

Exercise

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.

Instructions

100 XP
  • 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().