How does one turn a dictionary comprehension into a for loop

Viewed 40

I am pretty new to python and I more comfortable writing/reading for loops when I am trying to write a code. I came upon a code that someone wrote that can potentially help me with what I am trying to learn right now but I didn't really understand it because some of the code was written as a dictionary comprehension. I wanted to see if some can explain and help me convert the line of code "communities_dict" into a for loop instead of a dictionary comprehension. Thank you in advanced!

import community
import networkx as nx

# Generate test graph
G = nx.erdos_renyi_graph(30, 0.05)

# Relabel nodes

G = nx.relabel_nodes(G, {i: f"node_{i}" for i in G.nodes})

# Compute partition
partition = community.best_partition(G)

# Get a set of the communities
communities = set(partition.values())

# Create a dictionary mapping community number to nodes within that community

communities_dict = {c: [k for k, v in partition.items() if v == c] for c in communities}


 
1 Answers
for c in communities:
    tmp = []
    for k, v in partition.items():
        if v == c:
            tmp.append(k)
    communities_dict[c] = tmp
Related