对于普通字典:
mydict[new_key] = mydict.pop(old_key)
对于OrderedDict:
>>> OrderedDict(zip('123', 'abc'))
OrderedDict([('1', 'a'), ('2', 'b'), ('3', 'c')])
>>> oldkey, newkey = '2', 'potato'
>>> OrderedDict((newkey if k == oldkey else k, v) for k, v in _.viewitems())
OrderedDict([('1', 'a'), ('potato', 'b'), ('3', 'c')])
参考文章:https://stackoverflow.com/questions/16475384/rename-a-dictionary-key?answertab=votes#tab-top
网友评论