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.
just create a new dictionary:
new_dict = {my_mod(key): my_dict[key] for key in my_dict}
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()}
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