Python Programming Time is a column about high quality Python development
A series of reading
1. Python tricks that most people don’t know: Seven ways to write conditional statements
The Python language has many (and growing) advanced features that Python enthusiasts love. In their eyes, writing advanced features that the average developer can’t understand is a master, a god.
But you know, in teamwork, showmanship is a big no-no.
Why do you say that? Here’s what I think:
- The more concise the code, the clearer the logic, the less prone to error;
- In teamwork, your code is not maintained by you alone, and it is a good virtue to reduce the cost to others of reading/understanding the code logic
- Simple code that uses only the most basic syntax sugar, complex advanced features that have more dependencies (such as language versions)
This is the second in a series of tricks, in which I take stock of some of the tricks I’ve seen. Here, if you are a Python enthusiast, you can learn some cool code writing techniques. In the meantime, reading this may help you read other people’s code.
1. The easiest way to update in situ
The dictionary object has a built-in update method that updates 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'}
Copy the code
If you want to use update, the simplest and most native method, but don’t want to update yourself, but instead generate a new object, 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}
Copy the code
2. Unpack dictionaries before merging them
Unpack dictionaries with **, and then merge them with dict or {}.
>>> 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'}
Copy the code
If you don’t know what dict(**profile, **ext_info) does, you can equate it to
>>> dict((("name"."xiaoming"), ("age".27), ("gender"."male")))
{'name': 'xiaoming'.'age': 27.'gender': 'male'}
Copy the code
3. With the help of itertools
There is a very powerful built-in module in Python for manipulating iterable objects.
Itertools.chain () is used to chain multiple dictionaries together to form a larger iterable, and then dict is used to turn them into dictionaries.
>>> 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'}
Copy the code
4. With the help of ChainMap
If you can introduce a helper package, I’ll mention one more. ChainMap can do the same 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'}
Copy the code
One thing to note about ChainMap is that when there are duplicate keys between dictionaries, only the first value is taken, and the next key does not update the first one (this is not the case with iterTools).
>>> from collections import ChainMap
>>>
>>> profile = {"name": "xiaoming"."age": 27}
>>> ext_info={"age": 30}
>>> dict(ChainMap(profile, ext_info))
{'name': 'xiaoming'.'age': 27}
Copy the code
5. Merge with dict.items()
Before Python 3.9, actually has the | operator, but it is usually used to set (set) and set.
You can take advantage of this and use it for dictionary merging, but it takes a little bit of a detour.
You first use the items method to turn dict items into dict_items, then combine the two dict_items, and then use the dict function to turn dict items into dictionaries.
>>> 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'}
Copy the code
Of course, if this is too much trouble, you can simply use the list function to merge again (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'}
Copy the code
If you’re in Python 2.x, you can 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'}
Copy the code
6. The coolest dictionary interpretation
Python has a very Pythonnic way of generating lists, collections, and dictionaries.
List parsers, set parsers, and dictionary parsers are often favored by Python aficionados. But can dictionary parsers still do the job for today’s topic: dictionary merging?
Of course, the specific 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'}
Copy the code
7. New features in Python 3.9
Python 3.9.04 a version released in February, a new eye-catching new Operator operators: |, PEP584 call it merge Operator (the Union Operator), use it can merge multiple visual dictionary.
>>> 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} > > > > > >Copy the code
In addition to the | operator, another operator | =, similar to the in situ update.
>>> ext_info |= profile
>>> ext_info
{'gender': 'male'.'name': 'xiaoming'.'age': 27} > > > > > >>>> profile |= ext_info
>>> profile
{'name': 'xiaoming'.'age': 27.'gender': 'male'}
Copy the code
After learning Python for so long, I didn’t realize there were so many ways to merge dictionaries. The main idea of this article, is not that allows you to master all the seven ways to merge the dictionary, in the actual work, as long as you can choose one of the most comfortable way, but in the work or in reading others’ code, you will inevitably encounter all kinds of writing, you can subconsciously know merge the operation of the dictionary, it is doing Then this article makes sense.