Python runtime error dictionary
Question: I have made this code, I believe the problem is in Line 30 (32), I get the
following error about the dictionary **"RuntimeError: dictionary changed size
during iteration"** I am at a loss, a google search and a look around stack
overflow had some examples and similar issues but I cant seem to figure it
out, thanks for your help.

    
    
    import sys
    from collections import defaultdict
    from bisect import insort
    
    graph = defaultdict(list)
    edges = []
    with open("blu.txt") as f:
        for line in f:
            (key, val) = line.split()
            graph[key].append(val)
            graph[val].append(key)
            edges.append((key, val))
    
    k = 3
    change = True
    while change:
        change = False
        for edge in edges:
            inter = set(graph[edge[0]]).intersection(graph[edge[1]])
            if len(inter) < (k - 2):
                if edge[1] in graph[edge[0]]:
                    graph[edge[0]].remove(edge[1])
                    change = True
                if edge[0] in graph[edge[1]]:
                    graph[edge[1]].remove(edge[0])
                    change = True
    
    g = dict((key, value) for key, value in graph.items() if value)
    for key, v in g.items():
        for k, value in g.items():
            if key in value:
                g.pop(key, None)
    
    for key, value in g.items():
        a = []
        insort(a, key)
        for v in value:
            insort(a, v)
        print (tuple(a))
    
    
    # for x in graph:
    # print (x, graph[x])
    
    
    # def generate_edges(graph):
    #     edges = []
    #     for k in graph:
    #         for neighbour in graph[k]:
    #             edges.append((k, neighbour))
    #     return edges
    
    
    # print(generate_edges(graph))
    


Answer: You can't iterate over and mutate a dictionary at the same time, see below:

    
    
    for key, v in g.items():
        for k, value in g.items():
            if key in value:
                g.pop(key, None)    # You can't do this in a loop. What are you trying to accomplish in the end?
    

First of all, you're looping twice, for no particular reason. And then you're
popping while iterating over `g`. Can you give us a sample input and output
with more details?

