lovesoftlayeraj lovesoftlayeraj - 7 months ago 9
Python Question

How to get union of 2 lists of dictionaries in Python

I have 2 lists with the 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 to have an
array3
with union of the above 2 lists

array3:
[{'student': {'name': 'abc'}, 'address': 'add_abc'},
{'student': {'name': 'rst'}, 'address': 'add_rst'},
{'student': {'name': 'xyz'}, 'address': 'add_xyz'}]


How can I do that in Python?

Answer

They are lists, not arrays, but here is a 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 for i in a2 if i not in a1]

the value of a3 will be

[{'student': {'name': 'abc'}, 'address': 'add_abc'}, 
 {'student': {'name': 'xyz'}, 'address': 'add_xyz'}, 
 {'student': {'name': 'rst'}, 'address': 'add_rst'}]

If you want your resulting list to be sorted (by student name, for example), simply use sort method:

a3.sort(key=lambda x: x["student"]["name"])

and the resulting a3 would be:

[{'student': {'name': 'abc'}, 'address': 'add_abc'}, 
 {'student': {'name': 'rst'}, 'address': 'add_rst'},
 {'student': {'name': 'xyz'}, 'address': 'add_xyz'}] 

Normally you would simply use set(a1 + a2) but the problem here is that you have dicts inside your lists and they are unhashable, therefore they cannot be set items.

Comments