在字典中更改键的名称 [英] Change the name of a key in dictionary

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

问题描述



有没有直接的方法呢?

解决方案

通过两个步骤轻松完成:

  dictionary [new_key] = dictionary [old_key] 
del dictionary [old_key]

或者1步: p>

 字典[new_key] = dictionary.pop(old_key)

如果 dictionary [old_key] 未定义,则会引发 KeyError 。请注意,这个删除字典[old_key]

 >>> dictionary = {1:'one',2:'two',3:'three'} 
>>>>字典['ONE'] = dictionary.pop(1)
>>>字典
{2:'two',3:'three','ONE':'one'}
>>>字典['ONE'] = dictionary.pop(1)
追溯(最近呼叫最后):
文件< input>,第1行,< module>
KeyError:1


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

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

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