Python合并字典操作时同key的value应该如何相加,pythonvalue,x = { apple:


x = { 'apple': 1, 'banana': 2 }y = { 'banana': 10, 'pear': 11 }

需要把两个字典合并,最后输出结果是:

{ 'apple': 1, 'banana': 12, 'pear': 11 }

最后的结果中 banana 是 12 而不是 2 吧

>>> x = { 'apple': 1, 'banana': 2 }>>> y = { 'banana': 10, 'pear': 11 }>>> for k, v in y.items():...     if k in x.keys():...         x[k] += v...     else:...         x[k] = v... >>> x{'pear': 11, 'apple': 1, 'banana': 12}>>> 

利用collections.Counter可轻松办到

>>> x = { 'apple': 1, 'banana': 2 }>>> y = { 'banana': 10, 'pear': 11 }>>> from collections import Counter>>> X,Y = Counter(x), Counter(y)>>> z = dict(X+Y)>>> z

本人的写法:

>>>from collections import Counter>>>dict(Counter(x)+Counter(y))

上面两位的答案都是对的,我做了一下性能对比,你可以看下。

from collections import Counterx = { 'apple': 1, 'banana': 2 }y = { 'banana': 10, 'pear': 11 }def f():    i = 0    while 1:        if i == 10000:            break        for k, v in y.items():            if k in x.keys():                x[k] += v            else:                x[k] = v        i += 1def g():    i = 0    while 1:        if i == 10000:            break        X,Y = Counter(x), Counter(y)        z = dict(X+Y)        i += 1if __name__ == "__main__":    import timeit    tf = timeit.timeit(f, "from __main__ import f", number=10)    tg = timeit.timeit(g, "from __main__ import g", number=10)    print "f: %s\ng: %s" % (tf, tg)

输出:

f: 0.138742800623g: 1.37559758279

我的建议是,简单的功能自己手写就好。

编橙之家文章,

评论关闭