First list of dictionaries:
ldic_1 = [{'personId': '2DHSJ32N2'}, {'personId': '8SHFJW7BA'}, {'personId': '2KS4BA0X9'}, {'personId': '2H84XKNH1'}, {'personId': '2H7QW2J4S'}, {'personId': '2HAY258CG'}]
Second list of dictionaries:
ldic_2 = [{'id': '2DHSJ32N2', 'fname': 'Adam'}, {'id': '8SHFJW7BA', 'fname': 'Smith'}, {'id': '2KS4BA0X9', 'fname': 'Lara'}, {'id': '2H7QW2J4S', 'fname': 'Kane'}, {'id': '2H84XKNH1', 'fname': 'Donald'}, {'id': '2H86CEQDG', 'fname': 'Nastya'}, {'id': '2H95F5D81', 'fname': 'Karolina'}, {'id': '2HA7GUKPQ', 'fname': 'Sara'}, {'id': '2H7TPXZSN', 'fname': 'Harry'}, {'id': '2HARDNGSW', 'fname': 'Joe'}, {'id': '2HAS95FR5', 'fname': 'Jill'}, {'id': '2HAY258CG', 'fname': 'David'}]
Whenever the value of "personId" of ldic_1 matches with the value of "id" of ldic_2 then the ldic_2 will get updated and the expected result will be:
ldic_2 = [{'id': '2DHSJ32N2', 'fname': 'Adam'}, {'id': '8SHFJW7BA', 'fname': 'Smith'}, {'id': '2KS4BA0X9', 'fname': 'Lara'}, , {'id': '2H7QW2J4S', 'fname': 'Kane'}, {'id': '2H84XKNH1', 'fname': 'Donald'}, {'id': '2HAY258CG', 'fname': 'David'}]
I don't know how to do this. Please help and thanks.
CodePudding user response:
set_of_ids = {dic['personId'] for dic in ldic_1}
for dic in ldic_2:
if dic['id'] in set_of_ids:
del dic['fname']
Output :
[{'id': '2DHSJ32N2'},
{'id': '8SHFJW7BA'},
{'id': '2KS4BA0X9'},
{'id': '2H8C3J8VD', 'fname': 'Kane'},
{'id': '2H84XKNH1'},
{'id': '2H86CEQDG', 'fname': 'Nastya'},
{'id': '2H95F5D81', 'fname': 'Karolina'},
{'id': '2HA7GUKPQ', 'fname': 'Sara'},
{'id': '2H7TPXZSN', 'fname': 'Harry'},
{'id': '2HARDNGSW', 'fname': 'Joe'},
{'id': '2HAS95FR5', 'fname': 'Jill'},
{'id': '2HAY258CG'}]
CodePudding user response:
This would be an effective way of solving this (assuming that id
is unique):
ldic_1 = [{'personId': '2DHSJ32N2'}, {'personId': '8SHFJW7BA'}, {'personId': '2KS4BA0X9'}, {'personId': '2H84XKNH1'},
{'personId': '2H7QW2J4S'}, {'personId': '2HAY258CG'}]
ldic_2 = [{'id': '2DHSJ32N2', 'fname': 'Adam'}, {'id': '8SHFJW7BA', 'fname': 'Smith'},
{'id': '2KS4BA0X9', 'fname': 'Lara'}, {'id': '2H8C3J8VD', 'fname': 'Kane'},
{'id': '2H84XKNH1', 'fname': 'Donald'}, {'id': '2H86CEQDG', 'fname': 'Nastya'},
{'id': '2H95F5D81', 'fname': 'Karolina'}, {'id': '2HA7GUKPQ', 'fname': 'Sara'},
{'id': '2H7TPXZSN', 'fname': 'Harry'}, {'id': '2HARDNGSW', 'fname': 'Joe'},
{'id': '2HAS95FR5', 'fname': 'Jill'}, {'id': '2HAY258CG', 'fname': 'David'}]
adict = {elem['id']: elem for elem in ldic_2}
result = []
for elem in ldic_1:
if elem['personId'] in adict:
result.append(adict[elem['personId']])
# if you want one-liner:
# result = [adict[elem['personId']] for elem in ldic_1 if elem['personId'] in adict]
Output:
[{'id': '2DHSJ32N2', 'fname': 'Adam'}, {'id': '8SHFJW7BA', 'fname': 'Smith'}, {'id': '2KS4BA0X9', 'fname': 'Lara'}, {'id': '2H84XKNH1', 'fname': 'Donald'}, {'id': '2HAY258CG', 'fname': 'David'}]