Python is about to release the official version of 3.9
This article mainly introduces the operation of the dictionary:
1. The merge operation of the dictionary greatly simplifies the code, and the method is very simple. As shown in the figure below, if you merge the two dictionaries a and b
a = {1: 'a', 2: 'b', 3: 'c'}
b = {4: 'd', 5: 'e'}
c = a | b
print(c)
Print out c
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
At the same time, you can use the merge update operation |=, this operator can update the data of the original dictionary:
a = {1: 'a', 2: 'b', 3: 'c'}
b = {4: 'd', 5: 'e'}
a |= b
print(a)
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
When performing a merge operation, if the dictionary contains the same key, the result of the operation will use the key-value pair of the second dictionary:
a = {1: 'a', 2: 'b', 3: 'c', 6: 'in both'}
b = {4: 'd', 5: 'e', 6: 'but different'}
print(a | b)
{1: 'a', 2: 'b', 3: 'c', 6: 'but different', 4: 'd', 5: 'e'}