pat92 pat92 - 1 month ago 8
Python Question

Replace nested keys in a dictionary with values of another dictionary

At the moment I have two dictionaries
I want to change the inner keys with the values of the other dictionary

d1 = {1:{1: 2.0,2: 1.5,3: 5.0},
2:{1: 7.5,2: 6.0,3: 1.0}}
d2 = {1: 'a', 2: 'b', 3: 'c'}
expected output: {1:{'a': 2.0,'b': 1.5,'c': 5.0},
2:{'a': 7.5,'b': 6.0,'c': 1.0}}


Sadly these two dictionarys are filled with a lot of data and it takes a long time to iterate over d1 and call a method which iterates over d2 to replace the keys in d1.

Is it possible to change the inner key, value pair in a faster time?
I found a possibility to replace the keys of a simple dictionary:

d = {'x':1,'y':2,'z':3}
d1 = {'x':'a','y':'b','z':'c'}
d = {d1[k]:v for k,v in d.items()}

output: {'a': 1, 'c': 3, 'b': 2}


but not with a nested dictionary.

So now I have no idea how I can solve my problem.
Maybe one of you guys could help me please.

Answer

You may do it using nested dict comprehension as:

>>> d1 = {1:{1: 2.0,2: 1.5,3: 5.0},
...       2:{1: 7.5,2: 6.0,3: 1.0}}
>>> d2 = {1: 'a', 2: 'b', 3: 'c'}
>>> {a: {d2[k]: v for k, v in d.items()} for a, d in d1.items()}
{1: {'a': 2.0, 'c': 5.0, 'b': 1.5}, 2: {'a': 7.5, 'c': 1.0, 'b': 6.0}}

OR, using simple for loop as:

>>> for _, d in d1.items():  # Iterate over the "d1" dict
...     for k, v in d.items():  # Iterate in nested dict
...         d[d2[k]] = v  # Add new key based on value of "d2"
...         del d[k]   # Delete old key in nested dict
... 
>>> d1
{1: {'a': 2.0, 'c': 5.0, 'b': 1.5}, 2: {'a': 7.5, 'c': 1.0, 'b': 6.0}}

Second approach will update the original d1 dict, where as first approach will create the new dict object.