Rename a dictionary key

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

    In case someone wants to rename all the keys at once providing a list with the new names:

    def rename_keys(dict_, new_keys):
        """
         new_keys: type List(), must match length of dict_
        """
    
        # dict_ = {oldK: value}
        # d1={oldK:newK,} maps old keys to the new ones:  
        d1 = dict( zip( list(dict_.keys()), new_keys) )
    
              # d1{oldK} == new_key 
        return {d1[oldK]: value for oldK, value in dict_.items()}
    

提交回复
热议问题