简体   繁体   English

修改Python字典键

[英]Modifying Python dictionary keys

Is there any short and nice way to in place modify all keys of a python dict? 是否有任何简短而好的方法来修改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 . 只要my_modification(key)不是my_dict的原始键, 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. 在我的问题中,键都是整数-100 < key < 100 ,修改只是一个全局移位,所以最小的键变为零。

只需创建一个新词典:

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. 正如你所指出的那样,尝试修改dict的内联键总是会有覆盖某些键的危险。 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()}

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. 免责声明:不确定你会以这种方式获得任何东西,但是你想要以这种方式去做dien是安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM