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 need to be done:
1. Convert string into a list of values
2. Merge the two lists and add new key values
3. Remove duplicate elements
Step 1 passed The commonly used function eval() can do it. The second step requires adding a key value and adding elements. The third step uses the properties of set to achieve the effect of deduplication. But in the end, you need to convert the set collection into a list 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 result is:
{'c': [1, 2, 3, 4]}
But in batch processing, It is possible that one of the key values has only one element, causing the compiler to recognize it as an int type, 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 running result is:
Traceback (most recent call last): 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 does not recognize them 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 allow it to run normally. Here we take advantage of the feature that set will remove duplicate elements and add the same elements. However, if the elements in 'b' are empty, this method will also fail. Here you need to take advantage of the fact that the last element in the python list is allowed to be followed by a comma, and you can handle it as follows.
x={'a':'1,2,3','b':''} x['c']=list(set(eval(x['a']+','+x['b']))) del x['a'] del x['b'] print x
Running result:
{'c': [1, 2, 3]}
The last method can also handle the first two situations.
The above is the detailed content of Example code for using Python to merge dictionary key values and remove duplicate elements. For more information, please follow other related articles on the PHP Chinese website!