代码之家  ›  专栏  ›  技术社区  ›  matthewr

在python中添加词典

  •  0
  • matthewr  · 技术社区  · 6 年前

    如果我有两本字典 x={'a':1,'b':2} y={'a':1,'b':3}

    我想要输出 z={'a':2,'b':5} ,是否有 z=dict.add(x,y) 函数,或者我应该将两个词典转换为数据帧,然后将它们与 z=x.add(y) 是吗?

    3 回复  |  直到 6 年前
        1
  •  3
  •   Andrej Kesely    6 年前

    你可以用 Counter 在这种情况下,例如:

    from pprint import pprint
    from collections import Counter
    
    x={'a':1,'b':2}
    y={'a':1,'b':3}
    
    c = Counter()
    c.update(x)
    c.update(y)
    
    pprint(dict(c))
    

    输出:

    {'a': 2, 'b': 5}
    

    或使用 + 以下内容:

    from pprint import pprint
    from collections import Counter
    
    x={'a':1,'b':2}
    y={'a':1,'b':3}
    
    pprint(dict(Counter(x) + Counter(y)))
    
        2
  •  1
  •   jpp    6 年前

    collections.Counter 是一种自然的方法,但在计算字典键的并集之后,也可以使用字典理解:

    x = {'a':1, 'b':2}
    y = {'a':1, 'b':3}
    
    dict_tup = (x, y)
    
    keys = set().union(*dict_tup)
    z = {k: sum(i.get(k, 0) for i in dict_tup) for k in keys}
    
    print(z)
    
    {'a': 2, 'b': 5}
    
        3
  •  0
  •   Platos-Child    6 年前

    代码:

    from collections import Counter
    
    x = {"a":1, "b":2}
    y = {"a":1, "b":3}
    
    c = Counter(x)
    c += Counter(y)
    z = dict(c)
    print(z)
    

    输出:

    {'a': 2, 'b': 5}