我想更改Python字典中條目的鍵。 python
有沒有簡單的方法能夠作到這一點? spa
我尚未看到這個確切的答案: code
dict['key'] = value
您甚至能夠對對象屬性執行此操做。 經過執行如下操做使它們成爲字典: 對象
dict = vars(obj)
而後,您能夠像字典同樣操做對象屬性: three
dict['attribute'] = value
在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
若是您有複雜的字典,則表示該字典中有一個字典或列表: 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'}}
只需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
您能夠將相同的值與許多鍵相關聯,或者只刪除一個鍵並從新添加具備相同值的新鍵。
例如,若是您有鍵->值:
red->1 blue->2 green->4
沒有理由您不能添加purple->2
或刪除red->1
並添加orange->1