arrays - How to get union of 2 lists of dictionaries in Python -
i have 2 lists following data structure:
array1: [{'student': {'name': 'abc'}, 'address': 'add_abc'}, {'student': {'name': 'xyz'}, 'address': 'add_xyz'}] array2: [{'student': {'name': 'abc'}, 'address': 'add_abc'}, {'student': {'name': 'rst'}, 'address': 'add_rst'}]
i want have array3
union of above 2 lists
array3: [{'student': {'name': 'abc'}, 'address': 'add_abc'}, {'student': {'name': 'rst'}, 'address': 'add_rst'}, {'student': {'name': 'xyz'}, 'address': 'add_xyz'}]
how can in python?
they lists
, not arrays, here solution:
a1 = [{'student': {'name': 'abc'}, 'address': 'add_abc'}, {'student': {'name': 'xyz'}, 'address': 'add_xyz'}] a2 = [{'student': {'name': 'abc'}, 'address': 'add_abc'}, {'student': {'name': 'rst'}, 'address': 'add_rst'}] a3 = a1 + [i in a2 if not in a1]
the value of a3
be
[{'student': {'name': 'abc'}, 'address': 'add_abc'}, {'student': {'name': 'xyz'}, 'address': 'add_xyz'}, {'student': {'name': 'rst'}, 'address': 'add_rst'}]
if want resulting list sorted (by student name, example), use sort
method:
a3.sort(key=lambda x: x["student"]["name"])
and resulting a3
be:
[{'student': {'name': 'abc'}, 'address': 'add_abc'}, {'student': {'name': 'rst'}, 'address': 'add_rst'}, {'student': {'name': 'xyz'}, 'address': 'add_xyz'}]
normally use set(a1 + a2)
problem here have dict
s inside list
s , unhashable, therefore cannot set items.
Comments
Post a Comment