删除项后保留字典索引

时间:2014-11-24 07:07:18

标签: python dictionary

我正在迭代字典,如果某些条件匹配,那么我删除字典项。现在字典动态索引得到更新。

e.g。

{u'Titanic': {'match': [{'category': u'Book'},
                        {'category': u'Movie'},
                        {'category': u'Product'}],
              'score': 100}}

在迭代match时,如果我删除Book(索引 - 0),那么现在在下一次迭代中它会直接显示product(index - 1),考虑{{1在index-0上。它认为index-0已经迭代了。

代码剪辑:

movie

在这种情况下如何保持当前索引并迭代而不跳过任何项目。在上面的示例项 for k1,v1 in enumerate(value['match']): if k1 != '': print '\n Category: ',k1,' ',v1['category'] print 'Do you want to change the class of entity',k1 ,'? Y/N', 'Or delete', k1, '1/0' choice = raw_input() if choice == 'N' or choice == 'n': pass elif choice == 'Y' or choice == 'y' : print '\tEnter class : \t' v1['category'] = raw_input() tagged = string.replace(sentence, key, v1['category']) tagged_ans.append(tagged) elif choice == '1': del v1['category'] del value['match'][k1] 中被跳过

1 个答案:

答案 0 :(得分:1)

您可以简单地反向循环遍历循环。这样就可以根据需要从末尾删除元素,这样就不会替换你没有经过迭代的元素。

我们可以通过将您的枚举转换为列表,并使用reversed包装此列表来实现此目的:

for k1,v1 in reversed(list(enumerate(value['match']))):
    if k1 != '':
        print '\n Category: ',k1,' ',v1['category']

        print 'Do you want to change the class of entity',k1 ,'? Y/N', 'Or delete', k1, '1/0' 
        choice = raw_input()
        if choice == 'N' or choice == 'n':
            pass
        elif choice == 'Y' or choice == 'y' :
            print '\tEnter class : \t'
            v1['category'] = raw_input()
            tagged = string.replace(sentence, key, v1['category'])
            tagged_ans.append(tagged)
        elif choice == '1':
            del v1['category']
            del value['match'][k1]

因为我们要将它转换为列表,所以要小心在非常大的序列上使用它。如有必要,可以使用更有效的方法来创建列表(例如itertools)。