Replacing the keys in a dictionary based on the values of another


I have two dictionaries (Dic1 and Dict2)

Dict1 = {'M0': 399, 'M1': 71, 'M2': '0.979827269', 'M3': '0.84576281', 'M4': '0.011849132', 'M5': '0.066588785'}
Dict2 = {'M0': 'KPI1', 'M1': 'KPI2', 'M2': 'KPI3', 'M3': 'KPI4', 'M4': 'KPI5', 'M5': 'KPI6'}

I want to update the keys of Dict1 based on the key-value pairs in Dict 2.
So I want my output dictionary to look like

Dict1 = {'KPI1': 399, 'KPI2': 71, 'KPI3': '0.979827269', 'KPI4': '0.84576281', 'KPI5': '0.011849132', 'M5': '0.066588785'}
Asked By: z star



You can use a dict comprehension to create a new dict.

res = {Dict2[k] : v for k, v in Dict1.items()}
Answered By: Unmitigated
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.