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
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.