how to replace a key in dict python for loop

Question:

d={"given_age":"30","given_weight":"160","given_height":6}

want to remove "given_" from each of the key,

for key,value in d.items():
      new_key=re.sub(r'given_','',key)
      if new_key!=key:
            d[new_key]=d.pop(key)

getting below error, my intention is to change the key only, why does it complain?

RuntimeError: dictionary keys changed during iteration
Asked By: user2333234

||

Answers:

It is best not to modify collections when iterating over them. Use a dict comprehension here instead.

res = {re.sub('given_','',k) : v for k, v in d.items()}
Answered By: Unmitigated

You can also use str.replace() with dict comprehensiomn

d={"given_age":"30","given_weight":"160","given_height":6}

{key.replace('given_', '') : value for key, value in d.items()}

#{'age': '30', 'weight': '160', 'height': 6}

Edit as suggested by @CrazyChucky

{key.removeprefix('given_') : value for key, value in d.items()}
#{'age': '30', 'weight': '160', 'height': 6}
Answered By: God Is One

If you need to do this "in-place" and only change the keys that have the "given_" prefix, you could use the update method:

d.update((k[6:],d.pop(k)) for k in d if k.startswith("given_"))
Answered By: Alain T.
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.