Home > OS >  remove duplicates from value of dicts of list
remove duplicates from value of dicts of list

Time:11-02

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"}

CodePudding user response:

Just use set to track seen ids:

seen = set()
alist = [
    {"name": "name1", "zipcode": "zipcode1", "id": "id1"},
    {"name": "name2", "zipcode": "zipcode2", "id": "id2"},
    {"name": "name1", "zipcode": "zipcode3", "id": "id1"}
]
result = []
for obj in alist:
    idx = obj['id']
    if idx not in seen:
        result.append(obj)
    seen.add(idx)
print(result)

Output:

[{'name': 'name1', 'zipcode': 'zipcode1', 'id': 'id1'}, {'name': 'name2', 'zipcode': 'zipcode2', 'id': 'id2'}]

CodePudding user response:

Try this in one line:

l = [{"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 l}.values())

This is a little tricky, the point is that dictionaries can not have same key twice. by making the name as a dict key and get the values again you can achieve what you want.

  • Related