联盟的多个列表python

时间:2016-11-15 05:39:32

标签: python list union

如何在python中执行列表中所有子列表的dict对象元素的并集: 例如:

[
 [
  {'a':'b'}
 ],
 [
 { 'c':'d'} 
 ]
]
子列表1中pos 0处的

元素应与子列表2中的pos 0处的元素结合使用Ex OUTPUT:

  [
     [
      {
       'a':'b',
       'c':'d'
      } 

     ]
    ]

1 个答案:

答案 0 :(得分:0)

zip()列表和merge_dicts()

def merge_dicts(*args):
    r = {}
    for d in args:
        r.update(d)
    return r

>>> lst = [[{'a':'b'}],[{ 'c':'d'}]]
>>> [merge_dicts(*ds) for ds in zip(*lst)]
[{'a': 'b', 'c': 'd'}]
>>> lst = [[{'a':'b'},{1:2}],[{'c':'d'},{3:4}],[{'e':'f'},{5:6}]]
>>> [merge_dicts(*ds) for ds in zip(*lst)]
[{'a': 'b', 'c': 'd', 'e': 'f'}, {1: 2, 3: 4, 5: 6}]