max
max

Reputation: 52253

Rename dictionary keys according to another dictionary

(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 = change[k]
  new[k] = v
old = new

Upvotes: 4

Views: 1226

Answers (1)

John La Rooy
John La Rooy

Reputation: 304167

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

Upvotes: 11

Related Questions