gpt4 book ai didi

python - 更改字典中键的名称

转载 作者:IT老高 更新时间:2023-10-28 12:07:09 25 4
gpt4 key购买 nike

如何更改 Python 字典中条目的键?

最佳答案

两步轻松搞定:

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

或在 1 步中:

dictionary[new_key] = dictionary.pop(old_key)

如果 dictionary[old_key] 未定义,则会引发 KeyError。请注意,这删除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

关于python - 更改字典中键的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4406501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com