Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 573
xennygrimmato Avatar asked Oct 27 '16 12:10

xennygrimmato


People also ask

Which function is used to return all keys of dict?

The dict. keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion.

Should I use dict () or {}?

tl;dr. With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.

Can you put functions in a dictionary Python?

Given a dictionary, assign its keys as function calls. Case 1 : Without Params. The way that is employed to achieve this task is that, function name is kept as dictionary values, and while calling with keys, brackets '()' are added.


1 Answers

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.

like image 74
brianpck Avatar answered Sep 29 '22 13:09

brianpck