Shagboy
Shagboy

Reputation: 23

Remove duplicate of a dictionary from list

How can i remove duplicate of the key "name"

[  
   {  
      'items':[  
         {  
            '$oid':'5a192d0590866ecc5c1f1683'
         }
      ],
      'image':'image12',
      '_id':{  
         '$oid':'5a106f7490866e25ddf70cef'
      },
      'name':'Amala',
      'store':{  
         '$oid':'5a0a10ad90866e5abae59470'
      }
   },
   {  
      'items':[  
         {  
            '$oid':'5a192d2890866ecc5c1f1684'
         }
      ],
      'image':'fourth shit',
      '_id':{  
         '$oid':'5a106fa190866e25ddf70cf0'
      },
      'name':'Amala',
      'store':{  
         '$oid':'5a0a10ad90866e5abae59470'
      }
   }
]

I want to marge together dictionary with the same key "name"

Here is what i have tried

b = []

for q in data:
    if len(data) == 0:
        b.append(q)
    else:
        for y in b:
            if q['name'] != y['name']:
                b.append(q)

but after trying this the b list doesn't return unique dictionary that i wanted

Upvotes: 2

Views: 249

Answers (1)

user2390182
user2390182

Reputation: 73450

You loop through the assembled list and if you find a dict with a different name, you add the current dict. The logic should be different: only add it if you don't find one with the same name!

That being said, you should maintain a set of seen names. That will make the check more performant:

b, seen = [], set()

for q in data:
    if q['name'] not in seen:
        b.append(q)
        seen.add(q['name'])

Upvotes: 1

Related Questions