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

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

问题描述

我想更改 Python 字典中某个条目的键.

有没有直接的方法可以做到这一点?

解决方案

只需 2 个步骤即可轻松完成:

dictionary[new_key] = dictionary[old_key]删除字典[old_key]

或者一步:

dictionary[new_key] = dictionary.pop(old_key)

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

<预><代码>>>>字典 = { 1: '一', 2:'二', 3:'三' }>>>字典['ONE'] = dictionary.pop(1)>>>字典{2:'二',3:'三','一':'一'}>>>字典['ONE'] = dictionary.pop(1)回溯(最近一次调用最后一次):文件<input>",第 1 行,在 <module> 中关键错误: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天全站免登陆