如何在Python中获得2个字典列表的联合

时间:2016-04-19 06:34:01

标签: python arrays

我有2个列表,其中包含以下数据结构:

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

我希望array3拥有以上2个列表的联合

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

我怎么能用Python做到这一点?

1 个答案:

答案 0 :(得分:5)

它们是lists,而不是数组,但这是一个解决方案:

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]

a3的值将为

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

如果您希望对结果列表进行排序(例如,按学生姓名),只需使用sort方法:

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

,结果a3将是:

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

通常情况下,您只需使用set(a1 + a2),但问题是您dict内有list个且它们不可用,因此无法设置项目。