更改字典中键的名称

我想更改Python字典中条目的键。

有一种直截了当的方法吗?


慕的地10843
浏览 930回答 3
3回答

沧海一幻觉

轻松完成两个步骤: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):&nbsp; File "<input>", line 1, in <module>KeyError: 1

白衣非少年

如果你想更改所有键: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}如果您想更改单个密钥:您可以使用上述任何建议。

白猪掌柜的

在python 2.7及更高版本中,您可以使用字典理解:这是我在使用DictReader读取CSV时遇到的示例。用户使用':'为所有列名添加了后缀{'key1:' :1, 'key2:' : 2, 'key3:' : 3}摆脱键中的尾随':':corrected_dict = { k.replace(':', ''): v for k, v in ori_dict.items() }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python