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'}
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
d['info']
this should return for you list of users as u wish
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()
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)
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'}
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
d['info']
this should return for you list of users as u wish
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()
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)