Rename a dictionary key

后端 未结 12 872
盖世英雄少女心
盖世英雄少女心 2020-11-22 16:54

Is there a way to rename a dictionary key, without reassigning its value to a new name and removing the old name key; and without iterating through dict key/value?

I

12条回答
  •  生来不讨喜
    2020-11-22 17:32

    You can use this OrderedDict recipe written by Raymond Hettinger and modify it to add a rename method, but this is going to be a O(N) in complexity:

    def rename(self,key,new_key):
        ind = self._keys.index(key)  #get the index of old key, O(N) operation
        self._keys[ind] = new_key    #replace old key with new key in self._keys
        self[new_key] = self[key]    #add the new key, this is added at the end of self._keys
        self._keys.pop(-1)           #pop the last item in self._keys
    

    Example:

    dic = OrderedDict((("a",1),("b",2),("c",3)))
    print dic
    dic.rename("a","foo")
    dic.rename("b","bar")
    dic["d"] = 5
    dic.rename("d","spam")
    for k,v in  dic.items():
        print k,v
    

    output:

    OrderedDict({'a': 1, 'b': 2, 'c': 3})
    foo 1
    bar 2
    c 3
    spam 5
    

提交回复
热议问题