Rename a dictionary key

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

提交回复
热议问题