Python 重命名字典的键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30720673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Renaming the keys of a dictionary
提问by BarryPye
How to change a key in a Python dictionary?
如何更改 Python 字典中的键?
A routine returns a dictionary. Everything is OK with the dictionary except a couple keys need to be renamed. This code below copies the dictionary entry (key=value) into a new entry with the desired key and then deletes the old entry. Is there a more Pythonic way, perhaps without duplicating the value?
例程返回字典。除了需要重命名几个键之外,字典一切正常。下面的代码将字典条目(键=值)复制到具有所需键的新条目中,然后删除旧条目。有没有更 Pythonic 的方式,也许不复制价值?
my_dict = some_library.some_method(scan)
my_dict['qVec'] = my_dict['Q']
my_dict['rVec'] = my_dict['R']
del my_dict['Q'], my_dict['R']
return my_dict
采纳答案by Bhargav Rao
dict
keys are immutable. That means that they cannot be changed. You can read more from the docs
dict
键是不可变的。这意味着它们无法更改。您可以从文档中阅读更多内容
dictionaries are indexed by keys, which can be any immutable type
字典由键索引,键可以是任何不可变类型
Here is a workaround using dict.pop
这是使用的解决方法 dict.pop
>>> d = {1:'a',2:'b'}
>>> d[3] = d.pop(1)
>>> d
{2: 'b', 3: 'a'}