Rename a dictionary key

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

提交回复
热议问题