I have a list of dictionaries with a list of values
[{'name': ['TO_MATCH_1', 'TO_MATCH_2'], 'amount': ['2', '1']},
{'name': ['TO_MATCH_3', 'TO_MATCH_2'], 'amount': ['3', '4']}]
If the list of values under name
match the values of a second dictionary:
{'ONE': 'TO_MATCH_1',
'TWO': 'TO_MATCH_2',
'THREE': 'TO_MATCH_3',
'FOUR': 'TO_MATCH_4'}
The list is to be replaced with the keys of the second.
Expected output:
[{'name': ['ONE', 'TWO'], 'amount': ['2', '1']},
{'name': ['THREE', 'TWO'], 'amount': ['3', '4']}]
CodePudding user response:
# DATA
d1 = [{'name': ['TO_MATCH_1', 'TO_MATCH_2'], 'amount': ['2', '1']},
{'name': ['TO_MATCH_3', 'TO_MATCH_2'], 'amount': ['3', '4']}]
d2 = {'ONE': 'TO_MATCH_1',
'TWO': 'TO_MATCH_2',
'THREE': 'TO_MATCH_3',
'FOUR': 'TO_MATCH_4'}
d3 = {v: k for k, v, in d2.items()}
[{k: [d3.get(x, x) for x in v] for k, v in el.items()} for el in d1]
# [{'name': ['ONE', 'TWO'], 'amount': ['2', '1']},
# {'name': ['THREE', 'TWO'], 'amount': ['3', '4']}]
CodePudding user response:
You could reverse the mapping dictionary and use it in loop to replace values:
r_map = {v:k for k,v in mapping.items()}
for d in lst:
for i, name in enumerate(d['name']):
d['name'][i] = r_map.get(name, name)
print(lst)
Output:
[{'name': ['ONE', 'TWO'], 'amount': ['2', '1']},
{'name': ['THREE', 'TWO'], 'amount': ['3', '4']}]