更改字典中键的名称

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

有没有简单的方法能够作到这一点? spa


#1楼

我尚未看到这个确切的答案: code

dict['key'] = value

您甚至能够对对象属性执行此操做。 经过执行如下操做使它们成为字典: 对象

dict = vars(obj)

而后,您能够像字典同样操做对象属性: three

dict['attribute'] = value

#2楼

在python 2.7和更高版本中,您能够使用字典理解:这是我在使用DictReader读取CSV时遇到的示例。 用户已在全部列名后添加“:” input

ori_dict = {'key1:' : 1, 'key2:' : 2, 'key3:' : 3} it

摆脱键后面的“:”: io

corrected_dict = { k.replace(':', ''): v for k, v in ori_dict.items() } ast


#3楼

若是您有复杂的字典,则表示该字典中有一个字典或列表: module

myDict = {1:"one",2:{3:"three",4:"four"}}
myDict[2][5] = myDict[2].pop(4)
print myDict

Output
{1: 'one', 2: {3: 'three', 5: 'four'}}

#4楼

只需2个步骤便可轻松完成:

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

#5楼

您能够将相同的值与许多键相关联,或者只删除一个键并从新添加具备相同值的新键。

例如,若是您有键->值:

red->1
blue->2
green->4

没有理由您不能添加purple->2或删除red->1并添加orange->1

相关文章
相关标签/搜索