Rename dictionary keys according to another dictionary

(In Python 3)

I have a dictionary old. I need to change some of his keys; the keys that need to be changed and the corresponding new keys are stored in the dictionary change. What a good way to do this? Please note that there may be an overlap between old.keys()and change.values()that requires me to carefully apply this change.

The following code will (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
+3
source share
1 answer
old = {change.get(k,k):v for k,v in old.items()}
+9
source

Source: https://habr.com/ru/post/1770712/


All Articles