python – Rename dictionary keys according to another dictionary – Education Career Blog

(In Python 3)

I have dictionary old. I need to change some of its keys; the keys that need to be changed and the corresponding new keys are stored in a dictionary change. What’s a good way to do it? Note that there may be an overlap between old.keys() and change.values(), which requires that I’m careful applying the change.

The following code would (I think) work but I was hoping for something more concise and yet Pythonic:

new = {}
for k, v in old.items():
  if k in change:
    k = changek
  newk = v
old = new


old = {change.get(k,k):v for k,v in old.items()}

Leave a Comment