Issue
I have a list like this:
list = [{"name": "name1", "zipcode": "zipcode1", "id": "id1"},{"name": "name2", "zipcode": "zipcode2", "id": "id2"}, {"name": "name1", "zipcode": "zipcode3", "id": "id1"}]
I want to remove dicts which has same ids. I know how to remove duplicates but notice they are not duplicates, they have different zipcodes.
I expect this:
list2 = [{"name": "name1", "zipcode": "zipcode1", "id": "id1"},{"name": "name2", "zipcode": "zipcode2", "id": "id2"}
Solution
Try this in one line:
list1 = [{"name": "name1", "zipcode": "zipcode1", "id": "id1"},{"name": "name2", "zipcode": "zipcode2", "id": "id2"}, {"name": "name1", "zipcode": "zipcode3", "id": "id1"}]
list({i["name"]: i for i in list1}.values())
This is a little tricky, the point is that dictionaries can not have a same key twice. by making the name as a dictionary key and the rest as values.
By getting the values again. you will achieve what you want.
One more thing:
DO NOT use
list
as a variable name. list is predefined in python and you will override its own functionality bu doing this. some of common mistakes as a variable name are :list
,dict
,set
,input
, ...
Answered By - Mehrdad Pedramfar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.