How to change all the dictionary keys in a for loop with d.items()?

前端 未结 3 1176
庸人自扰
庸人自扰 2020-12-05 18:43

I would like some help with understanding why this code is not working as expected.

If one wants to change the key of a dictionary but keep the value, he/she might u

3条回答
  •  误落风尘
    2020-12-05 19:44

    in python3 dict.items() is just a view on the dict. as you are not allowed to modify an iterable while iterating you are not allowed to modify a dict while iterating over dict.items(). you have to copy items() to a list before iterating

    for k, v in list(name_dict.items()):
        ...
        name_dict[new_key] = name_dict.pop(k)
    

    this does fulfill your 'no new dict' requirement, although the list holds in fact a full copy of all your data.

    you could relax the memory footprint a little by copying just the keys

    for k in list(name_dict):
        v = name_dict.pop(k)
        ...
        name_dict[new_key] = v
    

    EDIT: credits to Sven Krüger, he raised the possibility of a old-key-new-key collision problem. in that case you have to go for

    kv = list(name_dict.items())
    name_dict.clear()
    for k, v in kv :
        ...
        name_dict[new_key] = v
    

    by the way, there is a use case for not creating a new dict, the current one might be referenced somwhere else.

提交回复
热议问题