Reputation: 497
I want to replace a value list in a dictionary using the values of another two dictionaries. For example, i have a dictionary with name "a_dict" for which each key have value as a list
a_dict = {'A1':[10,20,30,40,50,60,70],'B1':[30,50,60,70,80]}
Now i need to replace those values in a_dict which matches with "old_dict" using a new_dict as shown below,
old_dict = {0: 10, 1: 30}
new_dict = {0: 100, 1: 300}
So that the new a_dict should be,
a_dict_new = {'A1':[100,20,300,40,50,60,70],'B1':[300,50,60,70,80]}
I tried to come up with below code, but it does not give me correct solution,
a_dict = {'A1':[10,20,30,40,50,60,70],'B1':[30,50,60,70,80]}
old_dict = {0: 10, 1: 30}
new_dict = {0: 100, 1: 300}
#a_dict_new = {'A1':[100,20,300,40,50,60,70],'B1':[300,50,60,70,80]}
a_dict_new = {}
for ky1, val1 in old_dict.items():
for ky2, ls in a_dict.items():
new_ls=[]
for v in ls:
if (v==val1):
new_ls.append(new_dict[ky1])
else:
new_ls.append(v)
a_dict_new[ky2]=new_ls
#
print(a_dict_new)
OUTPUT 1: {'A1': [10, 20, 300, 40, 50, 60, 70], 'B1': [300, 50, 60, 70, 80]}
In first iteration in the first for loop, value 10 is changed to 100 in a_dict_new but in second iteration, it overwrites the first replacement. Hence the output looks only changed for 30 to 300.
Can anyone suggest an efficient way to do this dictionary replacement operation python 3?
Upvotes: 2
Views: 926
Reputation: 164673
Your logic seems overcomplicated. You can just create a single mapping dictionary:
mapper = {old_dict[k]: new_dict[k] for k in old_dict.keys() & new_dict.keys()}
# {10: 100, 30: 300}
Then use this to remap values via a dictionary comprehension:
a_dict_new = {k: [mapper.get(val, val) for val in v] for k, v in a_dict.items()}
# {'A1': [100, 20, 300, 40, 50, 60, 70], 'B1': [300, 50, 60, 70, 80]}
Upvotes: 1