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 dicts inside lists , unhashable, therefore cannot set items.


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -