重命名字典键 [英] Rename a dictionary key

查看:114
本文介绍了重命名字典键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法重命名字典键,而不必将其值重新分配到新名称并删除旧的名称键;并且没有迭代通过dict键/值?


如果是OrderedDict,请执行相同操作,同时保持该键的位置。

Is there a way to rename a dictionary key, without reassigning its value to a new name and removing the old name key; and without iterating through dict key/value?

In case of OrderedDict, do the same, while keeping that key's position.

推荐答案

对于常规的dict,你可以使用:

For a regular dict, you can use:

mydict[new_key] = mydict.pop(old_key)

对于OrderedDict,我认为您必须使用理解来构建一个全新的。

For an OrderedDict, I think you must build an entirely new one using a comprehension.

>>> OrderedDict(zip('123', 'abc'))
OrderedDict([('1', 'a'), ('2', 'b'), ('3', 'c')])
>>> oldkey, newkey = '2', 'potato'
>>> OrderedDict((newkey if k == oldkey else k, v) for k, v in _.viewitems())
OrderedDict([('1', 'a'), ('potato', 'b'), ('3', 'c')])

修改密钥本身,作为这个问题似乎是要求,是不切实际的,因为dict键通常是不可变的对象,如数字,字符串或元组。而不是尝试修改密钥,重新分配值到一个新的密钥和删除旧密钥是如何在python中实现重命名。

Modifying the key itself, as this question seems to be asking, is impractical because dict keys are usually immutable objects such as numbers, strings or tuples. Instead of trying to modify the key, reassigning the value to a new key and removing the old key is how you can achieve the "rename" in python.

这篇关于重命名字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆