I have 2 list big of dictionaries.. these are the example:
a= [{'name':'A','color':'1'},
{'name':'B','color':'2'},
{'name':'C','color':'3'},
]
b=[{'name':'A','color':'2'},
{'name':'x','color':'4'},
{'name':'x', 'color': '8'},
{'name':'p','color':'5'},
]
I would to filter out B list based on "Name" on another dictionary and also keep the unique from the Name fields
I tried :
[i for i in a for i in (filter(lambda x: x['name'] == i['name'],b))]
The Results :
[{'name': 'A', 'color': '2'}]
This results is the opposite my expectation, it keep the similar name from 2 list..
What I expect :
[
{'name':'x','color':'8'},
{'name':'p','color':'5'},
]
I need all the results from the b list that doesn't contain in a.. and also delete the unique from the b list.. ('name' : 'x' only appear once)
CodePudding user response:
You could create a temporary dictionary of dictionaries keyed on the 'name' values from b. This will only keep the last dictionary for each name. The temporary dictionary creation process could skip names found in a as it goes. To get the final list of filtered dictionaries, convert the temporary dictionary's values into a list.
aNames = {ad['name'] for ad in a}
distinct = {bd['name']:bd for bd in b if bd['name'] not in aNames}
newb = list(distinct.values())
print(newb)
[{'name': 'x', 'color': '8'}, {'name': 'p', 'color': '5'}]
