Rename a dictionary key

后端 未结 12 743
盖世英雄少女心
盖世英雄少女心 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:28

    I am using @wim 's answer above, with dict.pop() when renaming keys, but I found a gotcha. Cycling through the dict to change the keys, without separating the list of old keys completely from the dict instance, resulted in cycling new, changed keys into the loop, and missing some existing keys.

    To start with, I did it this way:

    for current_key in my_dict:
        new_key = current_key.replace(':','_')
        fixed_metadata[new_key] = fixed_metadata.pop(current_key)
    

    I found that cycling through the dict in this way, the dictionary kept finding keys even when it shouldn't, i.e., the new keys, the ones I had changed! I needed to separate the instances completely from each other to (a) avoid finding my own changed keys in the for loop, and (b) find some keys that were not being found within the loop for some reason.

    I am doing this now:

    current_keys = list(my_dict.keys())
    for current_key in current_keys:
        and so on...
    

    Converting the my_dict.keys() to a list was necessary to get free of the reference to the changing dict. Just using my_dict.keys() kept me tied to the original instance, with the strange side effects.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-22 17:34

    @helloswift123 I like your function. Here is a modification to rename multiple keys in a single call:

    def rename(d, keymap):
        """
        :param d: old dict
        :type d: dict
        :param keymap: [{:keys from-keys :values to-keys} keymap]
        :returns: new dict
        :rtype: dict
        """
        new_dict = {}
        for key, value in zip(d.keys(), d.values()):
            new_key = keymap.get(key, key)
            new_dict[new_key] = d[key]
        return new_dict
    
    0 讨论(0)
  • 2020-11-22 17:37

    Other answers are pretty good.But in python3.6, regular dict also has order. So it's hard to keep key's position in normal case.

    def rename(old_dict,old_name,new_name):
        new_dict = {}
        for key,value in zip(old_dict.keys(),old_dict.values()):
            new_key = key if key != old_name else new_name
            new_dict[new_key] = old_dict[key]
        return new_dict
    
    0 讨论(0)
  • 2020-11-22 17:39

    In case of renaming all dictionary keys:

    target_dict = {'k1':'v1', 'k2':'v2', 'k3':'v3'}
    new_keys = ['k4','k5','k6']
    
    for key,n_key in zip(target_dict.keys(), new_keys):
        target_dict[n_key] = target_dict.pop(key)
    
    0 讨论(0)
  • 2020-11-22 17:45

    Using a check for newkey!=oldkey, this way you can do:

    if newkey!=oldkey:  
        dictionary[newkey] = dictionary[oldkey]
        del dictionary[oldkey]
    
    0 讨论(0)
提交回复
热议问题