如何从python中的列表中删除json字符串

时间:2015-11-16 12:54:27

标签: python json list

我有两个包含特定数据的列表我希望将它们合并到一个列表中并且没有重复。

list1 =[{"id": "123","Name": "Sam", "Age": 10},{"id": "124","Name": "Ajay", "Age": 10}]

list2 =[{"id": "123","Name": "Sam"},{"id": "124","Name": "Ajay"},{"id": "125","Name": "Ram"}]

输出列表应该是这样的

output= [{"id": "123","Name": "Sam", "Age": 10},{"id": "124","Name": "Ajay", "Age": 10},{"id": "125","Name": "Ram"}]

1 个答案:

答案 0 :(得分:1)

据推测,唯一标识信息的是id密钥。如果是这样,收集字典中两个列表的所有信息,然后从中生成一个新列表:

from itertools import chain

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

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

演示:

>>> 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'}]