Apply a function to all keys of a Python dict

python, python-2.7

Solution

You can use a dict comprehension:

>>> d = {1: 'a', 2: 'b', 3: 'c'}
>>> {k*100: v for k, v in d.items()}
{200: 'b', 300: 'c', 100: 'a'}

Replace `items()` with `iteritems()` if you're using Python 2.

Problem

I want to transform all the keys of a Python dict. For example, if the keys are integers, I want to change each key to be the original value multiplied by 100. What is the most performance-efficient way to achieve this? The way I am doing it right now is by storing the original keys in a `set` and deleting those keys, replacing them by new keys - this had a problem that if I had a `key=2` and a `key=200` in the original key set, there would be collision, which I would have to handle recursively until I find a key with no collision with the original key-set.

Original source