本文介绍了更改字典中键的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想更改 Python 字典中某个条目的键.
有没有直接的方法可以做到这一点?
解决方案
只需 2 个步骤即可轻松完成:
dictionary[new_key] = dictionary[old_key]删除字典[old_key]
或者一步:
dictionary[new_key] = dictionary.pop(old_key)
如果 dictionary[old_key]
未定义,则会引发 KeyError
.请注意,这将删除dictionary[old_key]
.
I want to change the key of an entry in a Python dictionary.
Is there a straightforward way to do this?
解决方案
Easily done in 2 steps:
dictionary[new_key] = dictionary[old_key]
del dictionary[old_key]
Or in 1 step:
dictionary[new_key] = dictionary.pop(old_key)
which will raise KeyError
if dictionary[old_key]
is undefined. Note that this will delete dictionary[old_key]
.
>>> dictionary = { 1: 'one', 2:'two', 3:'three' }
>>> dictionary['ONE'] = dictionary.pop(1)
>>> dictionary
{2: 'two', 3: 'three', 'ONE': 'one'}
>>> dictionary['ONE'] = dictionary.pop(1)
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: 1
这篇关于更改字典中键的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!