根据键值组合词典

时间:2016-08-29 11:03:53

标签: python

如何组合具有相同键的字典行。例如,如果我有

my_dict_list = [{'prakash': ['confident']},
 {'gagan': ['good', 'luck']},
 {'jitu': ['gold']},
 {'jitu': ['wins']},
 {'atanu': ['good', 'glory']},
 {'atanu': ['top', 'winner','good']}]

我的目标是获得

my_new_dict_list = [{'prakash': ['confident']},
 {'gagan': ['good', 'luck']},
 {'jitu': ['gold','wins']},
 {'atanu': ['good', 'glory','top', 'winner','good']}]

我如何在Python中做到这一点?

编辑:最终列表中的词典必须包含重复值(如果出现在起始列表中)。

4 个答案:

答案 0 :(得分:2)

您可以遍历列表中的dicts,并将键值对插入或附加到新的dict:

my_dict_list = [{'prakash': ['confident']},
                {'gagan': ['good', 'luck']},
                {'jitu': ['gold']},
                {'jitu': ['wins']},
                {'atanu': ['good', 'glory']},
                {'atanu': ['top', 'winner']}]


new_d = {}
for d in my_dict_list:
    for k, v in d.items():
        if k in new_d:
            new_d[k] += v
        else:
            new_d[k] = v

然后你需要从结果中列出一个列表:

l = [{k: v} for k, v in new_d.items()]
# [{'atanu': ['good', 'glory', 'top', 'winner']}, {'gagan': ['good', 'luck']}, {'prakash': ['confident']}, {'jitu': ['gold', 'wins']}]

您需要知道列表中项目的顺序可能会因此而改变。

答案 1 :(得分:1)

这是一个有效的例子:

from itertools import groupby

my_dict_list = [
    {'prakash': ['confident']},
    {'gagan': ['good', 'luck']},
    {'jitu': ['gold']},
    {'jitu': ['wins']},
    {'atanu': ['good', 'glory']},
    {'atanu': ['top', 'winner']}
]

my_new_dict_list = []
for k, g in groupby(my_dict_list, key=lambda x: sorted(x.keys())):
    ds = list(g)
    d = {}
    for k in ds[0].iterkeys():
        d[k] = sum([d[k] for d in ds], [])
    my_new_dict_list .append(d)

print my_new_dict_list

答案 2 :(得分:1)

my_dict_list = [{'prakash': ['confident']},
{'gagan': ['good', 'luck']},
{'jitu': ['gold']},
{'jitu': ['wins']},
{'atanu': ['good', 'glory']},
{'atanu': ['top', 'winner','good']}]

my_new_dict_list = []
tmp_dict = {}
order = []

for d in my_dict_list:
    for k, v in d.iteritems():
        if not k in order: order.append(k)
        tmp_dict.setdefault(k, []).extend(v)

my_new_dict_list = [ {x: tmp_dict[x] } for x in order ]

输出:

[{'prakash': ['confident']},
 {'gagan': ['good', 'luck']},
 {'jitu': ['gold', 'wins']},
 {'atanu': ['good', 'glory', 'top', 'winner', 'good']}]

答案 3 :(得分:0)

使用defaultdict的极简主义方法:

from collections import defaultdict

my_dict_list = [{'prakash': ['confident']},
 {'gagan': ['good', 'luck']},
 {'jitu': ['gold']},
 {'jitu': ['wins']},
 {'atanu': ['good', 'glory']},
 {'atanu': ['top', 'winner','good']}]

merged_dict = defaultdict(list)
for d in my_dict_list:
    for key, value in d.items():
        merged_dict[key].extend(value)
result = [{key:value} for key, value in merged_dict.items()]

print(result)

<强>输出

[{'prakash': ['confident']}, 
{'gagan': ['good', 'luck']}, 
{'atanu': ['good', 'glory', 'top', 'winner', 'good']}, 
{'jitu': ['gold', 'wins']}]