Skip to content Skip to sidebar Skip to footer

How To Remove A Json String From List In Python

I have two list with particular data I would like to merge them into a single list with out duplicates. list1 =[{'id': '123','Name': 'Sam', 'Age': 10},{'id': '124','Name': 'Ajay',

Solution 1:

Presumably it is the id key that uniquely identifies the information. If so, collect all the info from the two lists in a dictionary, then produce a new list from that:

from itertools import chain

per_id = {}
for info inchain(list1, list2):
    per_id.setdefault(info['id'], {}).update(info)

output = list(per_id.values())  # Python 2 and 3 compatible

Demo:

>>> from itertools import chain
>>> list1 = [{'Age': 10, 'id': '123', 'Name': 'Sam'}, {'Age': 10, 'id': '124', 'Name': 'Ajay'}]
>>> list2 = [{'id': '123', 'Name': 'Sam'}, {'id': '124', 'Name': 'Ajay'}, {'id': '125', 'Name': 'Ram'}]
>>> per_id = {}
>>> for info in chain(list1, list2):
...     per_id.setdefault(info['id'], {}).update(info)
...
>>> list(per_id.values())
[{'Age': 10, 'id': '123', 'Name': 'Sam'}, {'Age': 10, 'id': '124', 'Name': 'Ajay'}, {'id': '125', 'Name': 'Ram'}]

Post a Comment for "How To Remove A Json String From List In Python"