3 回答

TA贡献1824条经验 获得超5个赞
轻松完成两个步骤:
dictionary[new_key] = dictionary[old_key]
del dictionary[old_key]
或者一步到位:
dictionary[new_key] = dictionary.pop(old_key)
KeyError如果dictionary[old_key]未定义则会引发。请注意,这将删除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

TA贡献1155条经验 获得超0个赞
如果你想更改所有键:
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}
如果您想更改单个密钥:您可以使用上述任何建议。

TA贡献1893条经验 获得超10个赞
在python 2.7及更高版本中,您可以使用字典理解:这是我在使用DictReader读取CSV时遇到的示例。用户使用':'为所有列名添加了后缀
{'key1:' :1, 'key2:' : 2, 'key3:' : 3}
摆脱键中的尾随':':
corrected_dict = { k.replace(':', ''): v for k, v in ori_dict.items() }
添加回答
举报