Python glitz operation: seven ways to merge Dictionaries

Keywords: Programming Python less

WeChat official account: Python programming time.

Python language has many (and more and more) advanced features, which are very popular with Python enthusiasts. In the eyes of these people, to be able to write out the advanced features that ordinary developers can't understand is a master, a God.

But you know, in teamwork, showing off your skills is taboo.

Why do you say that? Let me say what I think:

  1. The more concise the code, the clearer the logic, the less prone to error;
  2. In teamwork, your code is not only maintained by you. It is a good moral character to reduce the cost of reading / understanding the code logic for others
  3. Simple code will only use the most basic syntax sugar, complex high-level features, and have more dependencies (such as language version)

This is the second part of "dazzle Technology Series". In this series, I will summarize and check the dazzle 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 help you to read other people's code.

1. The simplest in place update

The dictionary object has an update method built in 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 update, the simplest and most native method, but do not want to update to yourself, but to 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 before merging Dictionaries

Use * * to unpack the dictionary. After unpacking, use dict or {} to 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 know what dict(**profile, **ext_info) does, you can equate it with

>>> 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 that is dedicated to working with iteratable objects.

Just as our dictionary is also an iterative object, we can naturally think that we can use the itertools.chain() function to concatenate multiple dictionaries (iterative objects) to form a larger iterative object, and then use dict to turn it into a dictionary.

>>> 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 the help of ChainMap

If a supplementary package can be introduced, I will mention another one. ChainMap can achieve the same effect as itertools.

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

When using ChainMap, you need to pay attention to that when there are duplicate keys between dictionaries, only the first value will be taken, and the key value in the next row will not update the previous one (this problem will not occur if you use itertools).

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

5. Use dict.items() to merge

Before Python 3.9, there was actually a|operator, but it was usually used to take and combine set s.

Using this, we can also use it to merge dictionaries. It's just a detour. It's a bit hard to understand.

You have to use the items method to convert dict to dict items, then merge the two dict items, and finally use the dict function to convert to 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 think it's too troublesome, you can simply use the list function to merge (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 are in Python 2.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 parsing

Python has a very Python way to generate 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, can dictionary parsing be 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 was added: |, which is called Union Operator by PEP584. It can be used to merge multiple dictionaries intuitively.

>>> 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}
>>>
>>>

In addition to the | operator, there is another operator, | =, which is similar to in place update.

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

See here, do you have a rising posture? After learning Python for so long, I didn't expect there are so many ways to merge dictionaries. The purpose of this article is not to let you master all 7 There are several ways to merge dictionaries. In fact, you only need to choose the most convenient way in your work. However, in collaborative work or reading other people's code, you will inevitably encounter a variety of writing methods. At this time, you can subconsciously know that this is the operation of merging dictionaries, and this article is meaningful.

Posted by msing on Thu, 09 Apr 2020 10:28:23 -0700