我想更改 Python 字典中条目的键。
有没有一种简单的方法可以做到这一点?
只需两步即可轻松完成:
dictionary[new_key] = dictionary[old_key] del dictionary[old_key]
或在 1 步中:
dictionary[new_key] = dictionary.pop(old_key)
KeyError如果dictionary[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