Suppose there is a dictionary in Python as follows:
X={' a ': ' 1,2,3 ', ' B ': ' 2,3,4 '}
Needs to be merged into:
x={' C ': ' 1,2,3,4 '}
Three things to do:
1. Convert a string to a list of values
2. Merge two lists and add new key values
3. Remove duplicate elements
The 1th step can be done by using the commonly used function eval (), step 2nd needs to add a key value and add elements, the 3rd step takes advantage of the nature of the set set to achieve the effect of heavy, but finally need to convert set set to list. The code is as follows:
X={' a ': ' 1,2,3 ', ' B ': ' 2,3,4 '}
x[' C ']=list (Set (eval (x[' a ']) +eval (x[' B '))))
del x[' a ']
del x[' B '
] Print X
The output results are:
{' C ': [1, 2, 3, 4]}
However, in batch processing, there may be only 1 elements of one key value, causing the compiler to recognize the type int, resulting in an error.
X={' a ': ' 1,2,3 ', ' B ': ' 2 '}
x[' C ']=list (Set (eval (x[' a ']) +eval (x[' B '))))
del x[' a ']
del x[' B '
] Print X
The results of the operation are:
Traceback (most recent):
File "test.py", line 2, in <module>
x[' C ']=list (Set (eval (x[' a ')) +eval ( X[' B ']) Typeerror:can only
concatenate tuple (not "int") to tuple
The processing method is to artificially copy the elements in ' B ' so that the compiler is not recognized as int:
X={' a ': ' 1,2,3 ', ' B ': ' 2 '}
x[' C ']=list (Set (eval (x[' a ')) +eval (x[' B ']+ ', ' +x[' B ')))
del x[' a ']
del x[' B ']
Print X
This will work correctly. This uses the set to remove the feature of the repeating element and add the same element. However, if the element in ' B ' is empty, this method will also fail. Here you need to take advantage of the last element of the Python list to allow a comma to be followed by the following method.
X={' a ': ' 1,2,3 ', ' B ': ' '}
x[' C ']=list (Set (eval (x[' a ']+ ', ' +x[' B ')))
del x[' a ']
del x[' B ']
print X
Run Result:
{' C ': [1, 2, 3]}
The last method can also handle the first two cases.
This Python merge dictionary key values and remove duplicate elements of the example is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.