python3 .6 下 报错 RuntimeError: dictionary changed size during iteration

循环字典键值,删除不符合要求的键值对

def createTree(dataSet, minSup=1): #create FP-tree from dataset but don't mine
    headerTable = {}
    #go over dataSet twice
    for trans in dataSet:#first pass counts frequency of occurance
        for item in trans:
            headerTable[item] = headerTable.get(item, 0) + dataSet[trans]
    for k in headerTable.keys():  #此行报错=========================
        if headerTable[k] < minSup: 
            del(headerTable[k])
    freqItemSet = set(headerTable.keys())
    #print('freqItemSet: ',freqItemSet)
    if len(freqItemSet) == 0: return None, None  #if no items meet min support -->get out
    for k in headerTable:
        headerTable[k] = [headerTable[k], None] #reformat headerTable to use Node link 
    #print('headerTable: ',headerTable)
    retTree = treeNode('Null Set', 1, None) #create tree
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

报错如此下:

    for k in headerTable.keys():  #remove items not meeting minSup
RuntimeError: dictionary changed size during iteration
  • 1
  • 2

解决方式:
做如下替换。。

for k in list(headerTable.keys()):  #此行报错=========================
        if headerTable[k] < minSup: 
            del(headerTable[k])
  • 1
  • 2
  • 3
欢迎关注我的公众号:小秋的博客 CSDN博客:https://blog.csdn.net/xiaoqiu_cr github:https://github.com/crr121 联系邮箱:rongchen633@gmail.com 有什么问题可以给我留言噢~
原文地址:https://www.cnblogs.com/flyingcr/p/10326937.html