Python - 如何通过键组合两个词典

时间:2017-12-20 05:42:45

标签: python dictionary union itertools

我有两个词:

A={'a':{"total":5,"all":[100,101]},'b':{"total":10,"all":[200,201]}}
B={'a':{"q1":"a","q2":"aa"},'b':{"q1":"b"},'c':{"q1":"c","q2":"ccc"}}

我根据键(a,b,c)组合了dicts中的所有值,如下所示:

import collections
super_dict = collections.defaultdict(set)
for k, v in chain(A.items(), B.items()):
    #related_datasets = v.get("all")
    #total_downloads = v.get("total")
    #query_1 = v.get("q1")
    #query_2 = v.get("q2")
    super_dict.setdefault(k, []).append(v)

这导致了(super_dict):

defaultdict(set,
            {'a': [{'all': [100, 101], 'total': 5}, {'q1': 'a', 'q2': 'aa'}],
             'b': [{'all': [200, 201], 'total': 10}, {'q1': 'b'}],
             'c': [{'q1': 'c', 'q2': 'ccc'}]})

但是,我想生成一个super_dict,如下所示:

{'a': {'all': [100, 101], 'q1': 'a', 'q2': 'aa', 'total': 5},
 'b': {'all': [200, 201], 'q1': 'b', 'total': 10},
 'c': {'q1': 'c', 'q2': 'ccc'}}

任何帮助将不胜感激。

好的,我找到了解决方案:

import collections
super_dict = {}
for k, v in chain(A.items(), B.items()):
    related_datasets = v.get("all")
    total_downloads = v.get("total")
    query_1 = v.get("q1")
    query_2 = v.get("q2")
    vkeys = v.keys()
    if k in super_dict.keys():
        super_dict[k].update(v)
    else:
        super_dict[k]= v

3 个答案:

答案 0 :(得分:3)

你很亲密:

A={'a':{"total":5,"all":[100,101]},'b':{"total":10,"all":[200,201]}}
B={'a':{"q1":"a","q2":"aa"},'b':{"q1":"b"},'c':{"q1":"c","q2":"ccc"}}

from itertools import chain
import collections
super_dict = collections.defaultdict(dict)
for k, v in chain(A.items(), B.items()):
    super_dict[k].update(v)
super_dict

答案 1 :(得分:1)

A={'a':{"total":5,"all":[100,101]},'b':{"total":10,"all":[200,201]}}
B={'a':{"q1":"a","q2":"aa"},'b':{"q1":"b"},'c':{"q1":"c","q2":"ccc"}}

d = {}

for key in set(A.keys() + B.keys()):
    try:
        d.setdefault(key,{}).update(A[key])        
    except KeyError:
        pass

    try:
        d.setdefault(key,{}).update(B[key])          
    except KeyError:
        pass

print d

<强>输出:

{'a': {'q1': 'a', 'q2': 'aa', 'all': [100, 101], 'total': 5}, 'c': {'q1': 'c', 'q2': 'ccc'}, 'b': {'q1': 'b', 'all': [200, 201], 'total': 10}}

答案 2 :(得分:0)

A={'a':{"total":5,"all":[100,101]},'b':{"total":10,"all":[200,201]}}  
B={'a':{"q1":"a","q2":"aa"},'b':{"q1":"b"},'c':{"q1":"c","q2":"ccc"}}

C = {}

C['a'] = {**A['a'], **B['a']}  
C['b'] = {**A['b'], **B['b']}  
C['c'] = {**B['c']}

print(C)
  

打印结果(C)使用最新版本的Python - C是你的   super_dict。
  {&#39; a&#39;:{&#39; all&#39;:[100,101],&#39; q1&#39;:&#39; a&#39;,&#39; q2&# 39;:&#39; aa&#39;,&#39; total&#39;:5},
  &#39; b&#39;:{&#39;所有&#39;:[200,201],&#39; q1&#39;:&#39; b&#39;,&#39;总计&#39 ;:10},
  &#39; c&#39;:{&#39; q1&#39;:&#39; c&#39;,&#39; q2&#39;:&#39; ccc&#39;}}