The following code finds communities for a given graph 'G', and assigns nodes within this graph values from 0-n, based on the community they fall into. The code then creates new sub-graphs for each community, and finds the node with the highest degree within each. Finally, the top node from each sub-graph is integrated into an overall dictionary:
G = 'max : john', 'max : tom', 'jim : john'....'jack : james'
node_partition = dict(community_louvain.best_partition(G))
print node_partition = max: 1, john: 0, james: 3, jim: 4,...tom: 0
"""number of communities = n = list(set(node_partition.values()))"""
dict0 = {k: v for k, v in node_partition.items() if v !=[0]}
G0 = G.copy()
G0.remove_nodes_from(dict0)
degree0 = dict(G.degree(G0))
degree0_dict = dict(sorted(degree0.items(), key=operator.itemgetter(1), reverse=True)[:1])
star_dict = {**degree0_dict, **degree1_dict....**degreek_dict)
This approach works, however a graph can have n amount of communities, and as you can see the code above is only for nodes in community 0. I have to manually read the amount of determined communities, and manually repeat and edit the code for each number. How can I apply a function which automatically repeats this code so instead of '0', I can have 'n'?