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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With