remove duplicate dictionaries

Question:

I have a dict

d = {'info': [{'name': 'Alice', 'Type': 'slave'}, {'name': 'Bob', 'Type': 'master'}, {'name': 'Bob', 'Type': 'slave'}]}

How can I do deletion so that in the output I get

{'name': 'Alice', 'Type': 'slave'}
{'name': 'Bob', 'Type': 'master'}
Asked By: petrvachovsky

||

Answers:

this should work:

d = {'info': [{'name': 'Alice', 'Type': 'slave'}, {'name': 'Bob', 'Type': 'master'}, {'name': 'Bob', 'Type': 'slave'}]}

out = []
usedNames = []

for person in d['info']:
    if not person['name'] in usedNames:
        out.append(person)
        usedNames.append(person['name'])

print(out) # [{'name': 'Alice', 'Type': 'slave'}, {'name': 'Bob', 'Type': 'master'}]

It returns you a list, tell me if it’s ok or if you want output in other formats

Answered By: Filippo Ferrario
d['info']

this should return for you list of users as u wish

Answered By: Baleweo

Your question is unclear. If you just want to remove value at the end of your dict. You can use:

> for key,value in d.items():
>     value.pop()
Answered By: Roshan

You should make a loop through the d[‘info’], add the items to another list if that item didn’t in that list. Here’s the code:

d = {'info': [{'name': 'Alice', 'Type': 'slave'}, {'name': 'Bob', 'Type': 'master'}, {'name': 'Bob', 'Type': 'slave'}]}


exist = []

for item in d["info"]:
    if item not in exist:
        exist.append(item)
        d["info"].remove(item)


print(exist)
Answered By: Avry G.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.