Unpack list of dictionaries in Python

╄→尐↘猪︶ㄣ 提交于 2020-01-24 07:24:26

问题


Question

According to this answer, in Python 3.5 or greater, it is possible to merge two dictionaries x and y by unpacking them:

z = {**x, **y}

Is it possible to unpack a variadic list of dictionaries? Something like

def merge(*dicts):
    return {***dicts} # this fails, of course. What should I use here?

For instance, I would expect that

list_of_dicts = [{'a': 1, 'b': 2}, {'c': 3}, {'d': 4}]
{***list_of_dicts} == {'a': 1, 'b': 2, 'c': 3, 'd': 4}

Note that this question is not about how to merge lists of dictionaries since the link above provides an answer to this. The question here is: is it possible, and how, to unpack lists of dictionaries?

Edit

As stated in the comments, this question is very similar to this one. However, unpacking a list of dictionaries is different from simply merging them. Supposing that there was an operator *** designed to unpack lists of dictionaries, and given

def print_values(a, b, c, d):
    print('a =', a)
    print('b =', b)
    print('c =', c)
    print('d =', d)

list_of_dicts = [{'a': 1, 'b': 2}, {'c': 3}, {'d': 4}]

it would be possible to write

print_values(***list_of_dicts)

instead of

print_values(**merge(list_of_dicts))

回答1:


There's no syntax for that, but you can use itertools.chain to concatenate the key/value tuples from each dict into a single stream that dict can consume.

from itertools import chain


def merge(*dicts):
    return dict(chain.from_iterable(d.items() for d in dicts))

You can use unpack a list created by a list comprehension as well:

def merge(*dicts):
    return dict(*[d.items() for d in dicts])



回答2:


You could just iterate over the list and use update:

lst = [{'a': 1, 'b': 2}, {'c': 3}, {'d': 4}]

dct = {}
for item in lst:
    dct.update(item)

print(dct)
# {'a': 1, 'b': 2, 'c': 3, 'd': 4}



回答3:


To merge multiple dictionaries you can use the function reduce:

from functools import reduce

lst = [{'a': 1, 'b': 2}, {'c': 3}, {'d': 4}]

reduce(lambda x, y: dict(**x, **y), lst)
# {'a': 1, 'b': 2, 'c': 3, 'd': 4}



回答4:


You could use list comprehension and put this iterable object as an argument to dict

def merge(*dicts):
    lst = [*[d.items() for d in dicts]]
    return dict(lst)


来源:https://stackoverflow.com/questions/58940431/unpack-list-of-dictionaries-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!