Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying Python dictionary keys

Is there any short and nice way to in place modify all keys of a python dict?

for key in my_dict.keys():
    my_dict[my_modification(key)] = my_dict.pop(key)

works as long as my_modification(key) is not as well an original key in my_dict. Otherwise, I get into trouble. In my problem, the keys are all integers -100 < key < 100 and the modification is just a global shift so that the smallest key becomes zero.

like image 804
Christian Avatar asked Jul 20 '26 05:07

Christian


2 Answers

just create a new dictionary:

new_dict = {my_mod(key): my_dict[key] for key in my_dict}
like image 84
acushner Avatar answered Jul 21 '26 17:07

acushner


Attempting to modify a dict's keys inline always bears the danger of overwriting some, as you've noted. Instead, it would be much easier to just create a new one:

my_modified_dict = \
{my_modification(key) : value for (key, value) in my_dict.iteritems()}
like image 37
Mureinik Avatar answered Jul 21 '26 17:07

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!