I have a list and a dictionary. I am trying to replace the values of the list in the dictionary with the values from the dictionary. I am trying to replace that are keys in the dictionary and keep the rest of the values as it is in the list. Here is the code I have -
list_1 = [[['bg_en', 'AB2_XY_EN', 'AB2'], ['AB2_MAN']], [['bg_en', 'CD2_XY_EN'], ['CD2_MAN']], [['bg_en', 'AB3_XY_EN'], ['AB3_MAN']]]
dict_1 = {'AB2_XY_EN': ['XY_EN ', 'XY_SEL'], 'CD2_XY_EN': ['XY_EN ', 'XY_SEL'], 'AB3_XY_EN': ['XY_EN ', 'XY_SEL']}
new_list_1 = []
for i in list_1:
sm_list_2 = []
for j in i:
sm_list_3 = []
for k in j:
for x, y in dict_1.items():
if k == x:
sm_list_3.append(y)
else:
sm_list_3.append(k)
sm_list_2.append(sm_list_3)
new_list_1.append(sm_list_2)
print(new_list_1)
I am not getting the desired output. The output I am looking got is of sort -
[[['bg_en', 'XY_EN ', 'XY_SEL', 'AB2'], ['AB2_MAN']], [['bg_en', 'XY_EN ', 'XY_SEL'], ['CD2_MAN']], [['bg_en', 'XY_EN ', 'XY_SEL'], ['AB3_MAN']]]
CodePudding user response:
your program needs a small change
list_1 = [[['bg_en', 'AB2_XY_EN', 'AB2'], ['AB2_MAN']], [['bg_en', 'CD2_XY_EN'], ['CD2_MAN']], [['bg_en', 'AB3_XY_EN'], ['AB3_MAN']]]
dict_1 = {'AB2_XY_EN': ['XY_EN ', 'XY_SEL'], 'CD2_XY_EN': ['XY_EN ', 'XY_SEL'], 'AB3_XY_EN': ['XY_EN ', 'XY_SEL']}
new_list_1 = []
for i in list_1:
sm_list_2 = []
for j in i:
sm_list_3 = []
for k in j:
# if the item is in dict, append the values from the dict, else just apend the item
sm_list_3 = dict_1.get(k, [k])
sm_list_2.append(sm_list_3)
new_list_1.append(sm_list_2)
print(new_list_1)
CodePudding user response:
I think recursion is a better solution
list_1 = [[['bg_en', 'AB2_XY_EN', 'AB2'], ['AB2_MAN']], [['bg_en', 'CD2_XY_EN'], ['CD2_MAN']], [['bg_en', 'AB3_XY_EN'], ['AB3_MAN']]]
dict_1 = {'AB2_XY_EN': ['XY_EN ', 'XY_SEL'], 'CD2_XY_EN': ['XY_EN ', 'XY_SEL'], 'AB3_XY_EN': ['XY_EN ', 'XY_SEL']}
def replace(list_):
temp = []
for i in list_:
if isinstance(i, list):
temp.append(replace(i))
elif v := dict_1.get(i):
temp.extend(v)
else:
temp.append(i)
return temp
print(replace(list_1))
Output
[[['bg_en', 'XY_EN ', 'XY_SEL', 'AB2'], ['AB2_MAN']], [['bg_en', 'XY_EN ', 'XY_SEL'], ['CD2_MAN']], [['bg_en', 'XY_EN ', 'XY_SEL'], ['AB3_MAN']]]