Christian
Christian

Reputation: 577

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.

Upvotes: 3

Views: 358

Answers (3)

holroy
holroy

Reputation: 3127

I would favour building a new dict as other answers suggest, but you could solve it in place if you extract all keys and sort them in reverse order before replacing in original dictionary.

In other words, in place replacing is possible if you make sure old and new keys not intermix, which in your case can be handled by reverse sorting keys before replacement.

Disclaimer: Not sure you'll gain anything doing it this way, but it is safely doable of you want to go dien that way.

Upvotes: 1

Mureinik
Mureinik

Reputation: 311073

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()}

Upvotes: 1

acushner
acushner

Reputation: 9946

just create a new dictionary:

new_dict = {my_mod(key): my_dict[key] for key in my_dict}

Upvotes: 7

Related Questions