Dictionary changed size during iteration while using pop() in python

Running through a json file remove all keys but one

for key in obj.keys():
        if key != 'multiverseId':
                print(key)
                obj.pop(key)

This is fine running python2 but in python3 you will run into this error

Calling keys() in python2 makes a copy of the keys that we iterate through. This is not how it works in python3, this returns an iterator instead of a list, hence the error we get while we try to run through the list and deleting keys. What we can do is converting in into a list

for key in list(obj.keys()):
        if key != 'multiverseId':
                obj.pop(key)
                print(key)
Tagged with: