从python中的词典列表合并词典

2024-09-30 14:21:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个字典列表,其中每个字典都有一个列表形式的值,如下所示:

dictlist=[{a:['e','f','g'],b:['h','i','k'],c:['u','v',w]},{a:['t','u']}]

上面的示例在列表中包含两个词典:

one is {a:['e','f','g'],b:['h','i','k'],c:['u','v',w]} 
and another dictionary is {a:['t','u']}

我只想组合这个列表的元素,以便生成一个完整的字典,其中包含列表中相同的键和值,如下所示:

finaldictionary = {a:['e','f','g','t','u'],b:['h','i',k],c:['u','v','w']}

Tags: and元素示例列表dictionary字典isanother
2条回答

您可以在此处使用^{}

>>> from collections import defaultdict

>>> dic=defaultdict(list)

>>> dictlist=[{'a':['e','f','g'],'b':['h','i','k'],'c':['u','v','w']},{'a':['t','u']}]

>>> for x in dictlist:
    for k,v in x.items():
        dic[k].extend(v)

>>> dic
defaultdict(<type 'list'>, {'a': ['e', 'f', 'g', 't', 'u'], 'c': ['u', 'v', 'w'], 'b': ['h', 'i', 'k']})

或使用dict.setdefault

>>> dic={}

>>> for x in dictlist:
        for k,v in x.items():
            dic.setdefault(k,[]).extend(v)

>>> dic
{'a': ['e', 'f', 'g', 't', 'u'], 'b': ['h', 'i', 'k'], 'c': ['u', 'v', 'w']}

“老派”的解决方案是这样的。。。你知道吗

finaldict = {}
dictlist = [{'a': ['e','f','g'], 'b': ['h','i','k'], 'c': ['u','v','w']},
            {'a': ['t','u']}]
for d in dictlist:
    for k in d.keys():
        try:
            finaldict[k] += d[k]
        except KeyError:
            finaldict[k] = d[k]

…这可能适用于自v1.0以来的所有Python版本,但有许多更新的方法可以做到这一点。你知道吗

相关问题 更多 >