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

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

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

 

利用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))

 

相关文章:

  • 2021-07-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-03-09
  • 2022-12-23
  • 2021-08-10
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-10-10
  • 2021-07-30
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案