Cannot rename Python dict key values with pop - Bug?

Viewed 104

I cannot rename the Python dict using pop as described below. I've used suggestions from this post. Is this a Python bug? I'm using Python 3.5.2

>>> d = {'a': 'ABC', 'b': 'CDE', 'c': 'KRT'}
>>> for old_key in d.keys():
        d['NEW_KEY_' + old_key] = d.pop(old_key)
>>> d

{'NEW_KEY_NEW_KEY_NEW_KEY_b': 'CDE', 'NEW_KEY_NEW_KEY_a': 'ABC', 'c': 'KRT'}
3 Answers

In Python 3, you have to change for old_key in d.keys() into for old_key in list(d.keys()). That should work because you are iterating over a dynamic entity.

It's mentioned in the documentation that changing a dictionary while iterating over it might fail to produce correct results. You'd better write something like

new_dict = {'NEW_KEY_' + key: value for key, value in old_dict.items()}

You are changing your keys as you iterate over a view of them. That's not recommended.

Instead, you can take a copy of your keys and iterate over them. Since dictionary keys are unique, you can use list or set:

d = {'a': 'ABC', 'b': 'CDE', 'c': 'KRT'}

for old_key in list(d):
    d['NEW_KEY_' + old_key] = d.pop(old_key)

# {'NEW_KEY_a': 'ABC', 'NEW_KEY_b': 'CDE', 'NEW_KEY_c': 'KRT'}

You can, of course, use a dictionary comprehension, which you should find more efficient.

Related