Reputation: 355
I am looking to replace all the keys in this dictionary -
L = [{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"}, {"VII":"S005"}, {"V":"S009"},{"VIII":"S007"}]
Here is the dataframe that has unique keys and name
dx new_col
0 VIII dx_1
1 VI dx_2
2 V dx_3
3 VII dx_4
The output I am looking is -
L = [{"dx_3":"S001"}, {"dx_3": "S002"}, {"dx_2": "S001"}, {"dx_2": "S005"}, {"dx_4":"S005"}, {"dx_3":"S009"},{"dx_1":"S007"}]
Upvotes: 1
Views: 55
Reputation: 71689
Create a mapping series from the given dataframe, then replace the keys using the mapping series inside a list comprehension
s = df.set_index('dx')['new_col']
[{s.get(k, k): v for k, v in d.items()} for d in L]
[{'dx_3': 'S001'},
{'dx_3': 'S002'},
{'dx_2': 'S001'},
{'dx_2': 'S005'},
{'dx_4': 'S005'},
{'dx_3': 'S009'},
{'dx_1': 'S007'}]
Upvotes: 2