[Python Fennel Bean Series] Dictionary Merger

[Python Fennel Bean Series] Dictionary Merger

Programming in Python, using different methods to accomplish the same goal, is sometimes a very interesting thing. This reminds me of Kong Yiji in Lu Xun's works. Kong Yiji has done a lot of research on the four writing styles of fennel beans. I dare not compare myself to Kong Yiji, here are some Python fennel beans, for all coders.

Suppose there are dictionaries x and y, BOSS needs to merge them to generate a new dictionary z, x and y remain unchanged. The effect to be achieved is as follows:

x = {
    
    'a': 1, 'b': 2}
y = {
    
    'b': 8, 'c': 9}

After processing

z = {
    
    'a': 1, 'b': 8, 'c': 9}

As a super beginner, the possible approach is:

>>> x = {
    
    'a': 1, 'b': 2}
>>> y = {
    
    'b': 8, 'c': 9}
>>> z = {
    
    }
>>> for k, v in x.items():
        z[k] = v
>>> for k, v in y.items():
        z[k] = v
>>> z
{
    
    'a': 1, 'b': 8, 'c': 9}

mission completed!
However, such a solution obviously did not catch Kong Yiji's eyes, so he began to count fennel beans.

fennel bean one: update

If your Python version is less than or equal to 3.4, then the following method should be the most common:

>>> z = x.copy()
>>> z.update(y)
>>> z
{
    
    'a': 1, 'b': 8, 'c': 9}

Fennel Bean II: Two Little Stars

If you have completely abandoned 2, and the Python version is greater than or equal to 3.5, then you can do this:

>>> z = {
    
    **x, **y}
>>> z
{
    
    'a': 1, 'b': 8, 'c': 9}

Fennel beans three: a vertical bar

What? Is your Python version greater than or equal to 3.9? All right:

>>> z = x | y
>>> z
{
    
    'a': 1, 'b': 8, 'c': 9}

Fennel Bean Four: ChainMap

ChainMap may be a bit unfamiliar to most developers, and its characteristic is: "preconceived", so pay attention to the order of the two dictionaries.

>>> from collections import ChainMap
>>> z = dict(ChainMap(y, x))
>>> z
{
    
    'a': 1, 'b': 8, 'c': 9}

Fennel Bean Five: Dict

Dict is a great thing, here are some examples. However, I don't recommend using it.

Why? Not elegant enough.

>>> z = dict(x, **y)  # 仅限于字典的 Key 均为 string 时有效
>>> z = dict(x.items() + y.items())  # Python 2
>>> z = dict(x.items() | y.items())

Guess you like

Origin blog.csdn.net/mouse2018/article/details/113469997