I have this
a = [{'name': 'John', 'supporterId': 1}, {'name': 'Paul', 'supporterId': 2}]
b = [{'dependent': 'Erick','supporterId': 2, 'email': '[email protected]'}, {'dependent': 'Anna', 'supporterId': 2, 'email': '[email protected]'}, {'dependent': 'George','supporterId': 13}]
and I need to check if the supporterId
between a
and b
are equal and if so put the name_dependent
and email inside the corresponding supporterId
in a
so for example the output to this should be:
c = [{'name': 'John', 'supporterId': 1}, {'name': 'Paul', 'supporterId': 2, 'data': {'dependent': 'Erick','email': '[email protected]'},
{'dependent': 'Ana','email':'[email protected]'}]
I have tried many for loops inside another but it doesn't seem to work...
CodePudding user response:
I suggest doing it in a couple of steps. First create a way to look up entries in b
by supporterId
:
>>> b_supporters = {d['supporterId']: d for d in b}
and then use that to build c
:
>>> c = [d | b_supporters.get(d['supporterId'], {}) for d in a]
producing:
>>> c
[{'name': 'John', 'supporterId': 1}, {'name': 'Paul', 'supporterId': 2, 'dependent': 'Anna', 'email': '[email protected]'}]
CodePudding user response:
I think this solves your problem:
c = []
for i, j in enumerate(a):
c.append(j)
c[i]['data'] = []
for k in b:
if j['supporterId'] == k['supporterId']:
c[i]['data'].append(k)
if not c[i]['data']:
del c[i]['data']
print(c)
Output:
[{'name': 'John', 'supporterId': 1}, {'name': 'Paul', 'supporterId': 2, 'data': [{'dependent': 'Erick', 'supporterId': 2, 'email': '[email protected]'}, {'dependent': 'Anna', 'supporterId': 2, 'email': '[email protected]'}]}]