xennygrimmato
xennygrimmato

Reputation: 2796

Apply a function to all keys of a Python dict

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.

Upvotes: 12

Views: 13507

Answers (3)

Alex
Alex

Reputation: 1151

I would use Dictionary Comprehension for this.

result = {your_func(key): value for key, value in your_dict.iteritems()}

Upvotes: 5

brianpck
brianpck

Reputation: 8254

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.

Upvotes: 17

chepner
chepner

Reputation: 531275

To add a dict comprehension answer that will work identically in Python 2.7 and Python 3.x:

{ your_func(key): your_dict[key] for key in your_dict }

It's even a little faster then items/iteritems (at least on my trivial test; profile your code to be sure).

# Python 2
>>> timeit.timeit( '{2*x: y for x,y in d.iteritems()}', 'd={1:2, 2:4}')
0.4100990295410156
>>> timeit.timeit( '{2*x: d[x] for x in d}', 'd={1:2, 2:4}')
0.38503098487854004

# Python 3
>>> timeit.timeit( '{2*x: y for x,y in d.items()}', 'd={1:2, 2:4}')
0.5370963809546083
>>> timeit.timeit( '{2*x: d[x] for x in d}', 'd={1:2, 2:4}')
0.4837625279906206

Upvotes: 1

Related Questions