Suppose that there is a dictionary in Python as follows:
x={' a ': ' 2,3,4 ', ' B ': ' A '
Need to be merged into:
x={' C ': ' 1,2,3,4 '}
There are 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 through the commonly used function eval () can be done, the 2nd step need to add a key value and add elements, 3rd step using the properties of set set can achieve the effect of the weight, but finally need to convert set set to list. The code is as follows:
X={' a ': ' 2,3,4 ', ' B ': '}x[', ' C ']=list (Set (eval (x[' a ')] +eval (x[' B '))) del x[' a ']del x[' B ']print x
The output is:
{' C ': [1, 2, 3, 4]}
However, in batch processing, there may be only 1 elements in one of the key values, which causes the compiler to recognize the int type, resulting in an error.
X={' a ': '}x[', ' B ': ' 2 ', ' C ']=list (Set (eval (x[' a ')] +eval (x[' B '))) del x[' a ']del x[' B ']print x
The result of the operation is:
Traceback (most recent): File "test.py", line 2, <module> x[' C ']=list (Set (eval (x[' a ')) +eval (x[' B ') ])) Typeerror:can only concatenate tuple (not "int.") to tuple
The approach is to artificially copy the elements in ' B ' so that the compiler does not recognize the int:
X={' a ': '}x[', ' B ': ' 2 ', ' C ']=list (Set (eval (x[' a ') ') +eval (x[' B ']+ ', ' +x[' B '))) del x[' a ']del x[' B ']print x
This will work as expected. This uses the set to remove the features of the repeating element, adding the same elements. However, if the element in ' B ' is empty, this method also fails. You need to take advantage of the nature of the last element in the Python list, followed by a comma, as follows.
X={' a ': ' X-ray ', ' B ': '}x[' C ']=list (Set (eval (x[' a ']+ ', ' +x[' B '))) del x[' a ']del x[' B ']print x
Operation Result:
{' C ': [1, 2, 3]}
The last method is also capable of handling the first two cases.