Python运行时错误字典

时间:2016-03-25 00:24:21

标签: python dictionary

我已经制作了这段代码,我相信问题出现在第30行(32)中,我得到以下关于字典的错误" RuntimeError:字典在迭代期间改变了大小" 我不知所措,谷歌搜索和浏览堆栈溢出有一些例子和类似的问题,但我似乎无法弄明白,谢谢你的帮助。

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))

2 个答案:

答案 0 :(得分:0)

你不能同时迭代并改变字典,见下文:

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?

首先,你没有特别的原因循环两次。然后你在迭代g时弹出。你能给我们一个带有更多细节的样本输入和输出吗?

答案 1 :(得分:0)

这一行 - g.pop(key,None) 您正在禁止的for循环中编辑字典 而是使用类似的东西 keys = g.keys() values = g.values() 然后迭代那些