python implements two examples of dict merge and compute operations

  • 2021-07-06 11:07:32
  • OfStack

In this paper, an example is given to describe the merger and calculation operation of two dict implemented by python. Share it for your reference, as follows:

Using the method of pythonic, two dict are combined and calculated. If key values are the same, their values will be added, otherwise, the original values will be retained.

Of course, it is usually thought that the loop method is used to do it, which is a well-known practice. Let's talk about a built-in method of python dict.

For example, there are two dictionaries:


Dict A: {'a':1, 'b':2, 'c':3}
Dict B: {'b':3, 'c':4, 'd':5}

The result after adding them is:

{'a':1, 'b':5, 'c':7, 'd':5}

The easiest way is to use the collections.Counter :


>>> from collections import Counter
>>> A = Counter({'a':1, 'b':2, 'c':3})
>>> B = Counter({'b':3, 'c':4, 'd':5})
>>> A + B
Counter({'c': 7, 'b': 5, 'd': 5, 'a': 1})

Counter is a subclass of dict, so you can use it as if you were using dict 1, such as


>>> C=A+B
>>> for item in C:
 print item,C.get(item)

Run results:

a 1
c 7
b 5
d 5

Refer to the website of this article: http://docs.python.org/library/collections.html # collections.Counter

For more readers interested in Python related contents, please check the topics of this site: "Summary of Python Dictionary Operation Skills", "Summary of Python List (list) Operation Skills", "Summary of Python Coding Operation Skills", "Summary of Python Function Use Skills", "Summary of Python String Operation Skills" and "Introduction and Advanced Classic Tutorial of Python"

I hope this article is helpful to everyone's Python programming.


Related articles: