根据字典键合并列表

时间:2018-06-12 16:05:15

标签: python

我有一个字典列表,如下所示:

list_dict = [{"hello": [1, 4, 4, 5, 2], "hi":["sjdgf", "sdlkfjsd", "sdfj", "sdfkj", "sdfkjd"], "namaste":[5, 6, 6, 2, 4]}, {"hello": [1, 4, 4, 5, 2], "hi":["sjdgf", "sdlsdfpjsd", "sdfj", "sdfkj", "sdfkjd"], "namaste":[5, 3, 6, 5, 4]}, {"hello": [1, 4, 4, 5, 2], "hi":["sjsdifjgf", "sdlkfjsd", "sdfj", "sdfkj", "sdfkjd"], "namaste":[5, 3, 6, 17, 4]}]

我想创建一个最终字典,它只是合并上面list_dict中每个字典的列表。我正在寻找的输出是:

final = {"hello": [1, 4, 4, 5, 2, 1, 4, 4, 5, 2, 1, 4, 4, 5, 2]], "hi":["sjdgf", "sdlkfjsd", "sdfj", "sdfkj", "sdfkjd", "sjdgf", "sdlsdfpjsd", "sdfj", "sdfkj", "sdfkjd", "sjsdifjgf", "sdlkfjsd", "sdfj", "sdfkj", "sdfkjd"], "namaste":[5, 6, 6, 2, 4, 5, 3, 6, 5, 4, 5, 3, 6, 17, 4]}

如何以可扩展的方式完成这项工作?

2 个答案:

答案 0 :(得分:2)

使用collections.defaultdict

<强>实施例

import collections
d = collections.defaultdict(list)
list_dict = [{"hello": [1, 4, 4, 5, 2], "hi":["sjdgf", "sdlkfjsd", "sdfj", "sdfkj", "sdfkjd"], "namaste":[5, 6, 6, 2, 4]}, {"hello": [1, 4, 4, 5, 2], "hi":["sjdgf", "sdlsdfpjsd", "sdfj", "sdfkj", "sdfkjd"], "namaste":[5, 3, 6, 5, 4]}, {"hello": [1, 4, 4, 5, 2], "hi":["sjsdifjgf", "sdlkfjsd", "sdfj", "sdfkj", "sdfkjd"], "namaste":[5, 3, 6, 17, 4]}]
for i in list_dict:
    for k, v in i.items():
        d[k].extend(v)
print(d)
print(d["hello"])

<强>输出:

defaultdict(<type 'list'>, {'namaste': [5, 6, 6, 2, 4, 5, 3, 6, 5, 4, 5, 3, 6, 17, 4], 'hi': ['sjdgf', 'sdlkfjsd', 'sdfj', 'sdfkj', 'sdfkjd', 'sjdgf', 'sdlsdfpjsd', 'sdfj', 'sdfkj', 'sdfkjd', 'sjsdifjgf', 'sdlkfjsd', 'sdfj', 'sdfkj', 'sdfkjd'], 'hello': [1, 4, 4, 5, 2, 1, 4, 4, 5, 2, 1, 4, 4, 5, 2]})

[1, 4, 4, 5, 2, 1, 4, 4, 5, 2, 1, 4, 4, 5, 2]

答案 1 :(得分:0)

您可以使用itertools.groupby

import itertools, functools
list_dict = [{"hello": [1, 4, 4, 5, 2], "hi":["sjdgf", "sdlkfjsd", "sdfj", "sdfkj", "sdfkjd"], "namaste":[5, 6, 6, 2, 4]}, {"hello": [1, 4, 4, 5, 2], "hi":["sjdgf", "sdlsdfpjsd", "sdfj", "sdfkj", "sdfkjd"], "namaste":[5, 3, 6, 5, 4]}, {"hello": [1, 4, 4, 5, 2], "hi":["sjsdifjgf", "sdlkfjsd", "sdfj", "sdfkj", "sdfkjd"], "namaste":[5, 3, 6, 17, 4]}]
new_list = [i for b in map(dict.items, list_dict) for i in b]
new_d = {a:functools.reduce(lambda x, y:x+y, [c for _, c in b]) for a, b in itertools.groupby(sorted(new_list, key=lambda x:x[0]),key=lambda x:x[0])}

输出:

{'hello': [1, 4, 4, 5, 2, 1, 4, 4, 5, 2, 1, 4, 4, 5, 2], 'hi': ['sjdgf', 'sdlkfjsd', 'sdfj', 'sdfkj', 'sdfkjd', 'sjdgf', 'sdlsdfpjsd', 'sdfj', 'sdfkj', 'sdfkjd', 'sjsdifjgf', 'sdlkfjsd', 'sdfj', 'sdfkj', 'sdfkjd'], 'namaste': [5, 6, 6, 2, 4, 5, 3, 6, 5, 4, 5, 3, 6, 17, 4]}