如何在python中对列表的所有子列表的dict对象的元素进行联合:例如:
[
[
{'a':'b'}
],
[
{ 'c':'d'}
]
]子列表1中位置0处的元素应与子列表2中位置0处的元素并集。Ex输出:
[
[
{
'a':'b',
'c':'d'
}
]
]发布于 2016-11-15 14:00:55
zip() up the lists和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}]https://stackoverflow.com/questions/40602776
复制相似问题