Python stunt operation that makes people want to curse: seven ways to merge Dictionaries

Time:2022-5-25

recommend:Python full stack tutorial! I spent 29980 to buy the course from introduction to mastery, and share it with you

Python stunt operation that makes people want to curse: seven ways to merge Dictionaries

There are many (and more and more) advanced features in the python language, which are very popular with Python enthusiasts. In the eyes of these people, being able to write advanced features that ordinary developers can’t understand is a master and a great God.

But you should know that in teamwork, dazzle technology is a big taboo.

Why do you say that? Let me say my opinion:

  1. The more concise the code and the clearer the logic, the less likely it is to make mistakes;

  2. In teamwork, you are not the only one who maintains your code. It is a good moral character to reduce the cost of others’ reading / understanding code logic

  3. Simple code only uses the most basic syntax sugar, complex advanced features and more dependencies (such as language version)

The article isDazzle Technology Series“In this series, I will summarize and take stock of the dazzling technology operations I have seen. Here, if you are a python enthusiast, you can learn some cool code writing skills. At the same time, reading these contents may be helpful for you when reading other people’s code.

1. The simplest in situ update

The dictionary object has a built-in update method, which is used to update another dictionary to itself.

>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info = {"gender": "male"}
>>>
>>> profile.update(ext_info)
>>> print(profile)
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}

If you want to use the simplest and most native method of update, but do not want to update yourself, but generate a new object, please use deep copy.

>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info = {"gender": "male"}
>>>
>>> from copy import deepcopy
>>>
>>> full_profile = deepcopy(profile)
>>> full_profile.update(ext_info)
>>>
>>> print(full_profile)
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}
>>> print(profile)
{"name": "xiaoming", "age": 27}

2. Unpack first and then merge dictionaries

use**You can unpack the dictionary, and then use dict or{}You can merge.

>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info = {"gender": "male"}
>>>
>>> full_profile01 = {**profile, **ext_info}
>>> print(full_profile01)
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}
>>>
>>> full_profile02 = dict(**profile, **ext_info)
>>> print(full_profile02)
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}

If you don’t knowdict(**profile, **ext_info)What did you do? You can equate it to

>>> dict((("name", "xiaoming"), ("age", 27), ("gender", "male")))
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}

3. With itertools

There is a very powerful built-in module in Python, which is specially used to manipulate iteratable objects.

It happens that our dictionary is also an iterative object. Naturally, we can think of it and use ititertools.chain()Function first connects multiple dictionaries (iteratable objects) to form a larger iteratable object, and then converts them into dictionaries using dict.

>>> import itertools
>>>
>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info = {"gender": "male"}
>>>
>>>
>>> dict(itertools.chain(profile.items(), ext_info.items()))
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}

4. With chainmap

If an auxiliary package can be introduced, I will mention another one,ChainMapCan also achieve anditertoolsThe same effect.

>>> from collections import ChainMap
>>>
>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info = {"gender": "male"}
>>>
>>> dict(ChainMap(profile, ext_info))
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}

One thing to note about using chainmap is that when there are duplicate keys between dictionaries, only the first value will be taken, and the key value in the back will not update the previous one (there will be no problem with using itertools).

>>> from collections import ChainMap
>>>
>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info={"age": 30}
>>> dict(ChainMap(profile, ext_info))
{'name': 'xiaoming', 'age': 27}

5. Merge with dict. Items()

Before Python 3.9, there were already|Operator, but it is usually used to merge sets.

Using this point, it can also be used for dictionary merging. It’s just a detour, which is a little difficult to understand.

You have to use it firstitemsMethods convert dict to dict_ Items, and then for these two dicts_ Items takes the union set, and finally uses the dict function to turn it into a dictionary.

>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info = {"gender": "male"}
>>>
>>> full_profile = dict(profile.items() | ext_info.items())
>>> full_profile
{'gender': 'male', 'age': 27, 'name': 'xiaoming'}

Of course, if you find this too troublesome, you can simply use the list function and merge it (Python 3. X for example)

>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info = {"gender": "male"}
>>>
>>> dict(list(profile.items()) + list(ext_info.items()))
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}

If you’re in Python 2 Under X, you can directly omit the list function.

>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info = {"gender": "male"}
>>>
>>> dict(profile.items() + ext_info.items())
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}

6. The coolest dictionary expression

Python has a very Python way of writing lists, sets and dictionaries.

That is list parsing, set parsing and dictionary parsing, which are usually the favorite of Python enthusiasts. So today’s topic: Dictionary merging, is dictionary parsing still competent?

Of course, the specific example code is as follows:

>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info = {"gender": "male"}
>>>
>>> {k:v for d in [profile, ext_info] for k,v in d.items()}
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}

7. New features of Python 3.9

In Python version 3.9.04a released in February, an eye-catching new operator is added:|, pep584 calls it the union operator, which can be used to intuitively merge multiple dictionaries.

>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info = {"gender": "male"}
>>>
>>> profile | ext_info
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}
>>>
>>> ext_info | profile
{'gender': 'male', 'name': 'xiaoming', 'age': 27}
>>>
>>>

except|In addition to the operator, there is another operator|=, similar to updating in place.

>>> ext_info |= profile
>>> ext_info
{'gender': 'male', 'name': 'xiaoming', 'age': 27}
>>>
>>>
>>> profile |= ext_info
>>> profile
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}

See here, is there a rising posture? After learning Python for so long, I didn’t expect that there are so many ways to merge dictionaries. The purpose of this article is not to let you master all the seven methods of merging dictionaries. In fact, you just need to choose the most convenient way.

However, in collaborative work or reading other people’s code, you will inevitably encounter various writing methods. At this time, you can subconsciously know that this is the operation of merging dictionaries, so this article is meaningful.

Recommended Today

Flutter practice – cross platform development

background With the convergence of mobile terminals from birth to development everywhere and then to platform, in order to continuously meet the enterprise’s pursuit of development efficiency and cross platform consistency, various cross platform solutions emerge in endlessly. For our product design and development, development efficiency and use experience are two crucial factors. If you […]