更改字典中键的名称

2024-04-19 22:09:59 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

新鲜的

>>>a = {1:2, 3:4}
>>>a[5] = a.pop(1)
>>>a
{3: 4, 5: 2}
>>> 

如果要更改所有密钥:

d = {'x':1, 'y':2, 'z':3}
d1 = {'x':'a', 'y':'b', 'z':'c'}

In [10]: dict((d1[key], value) for (key, value) in d.items())
Out[10]: {'a': 1, 'b': 2, 'c': 3}

如果要更改单键: 你可以接受上述任何建议。

分两步轻松完成:

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

或一步:

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

相关问题 更多 >