puncrazy
puncrazy

Reputation: 349

Persisting the dictionary index after deleting item

I am iterating through dictionary, if some condition match, then I delete the dictionary item. Now dictionary dynamically index gets updated.

e.g.

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

While iterating match, if I delete Book (index - 0), so now during next iteration it is showing me product (index - 1) directly, considering movie on index-0. It consider index-0 already iterated.

code snipped:

    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]

In such case how to persist current index and iterating without skipping any of the item. In above example item movie get skipped

Upvotes: 0

Views: 61

Answers (1)

grovesNL
grovesNL

Reputation: 6075

You may simply iterate through the loop in reverse. This way you delete elements from the end as necessary, which won't displace elements that you haven't iterated through.

We can do this by converting your enumeration to a list, and wrapping this list with 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]

Because we're casting it to a list, be careful about using this on extremely large sequences. If necessary, there are more efficient ways to do this without creating a list (such as itertools).

Upvotes: 1

Related Questions