Python combines dictionary key values and removes duplicate elements. python dictionary
Suppose there is a dictionary in python as follows:
X = {'A': '1, 2,3 ',' B ': '2, 3,4 '}
To merge:
X = {'C': '1, 2, 3, 4 '}
Three things need to be done:
1. convert a string to a Value List
2. merge two lists and add new key values
3. Remove duplicate elements
Step 1 can be achieved through the commonly used function eval (). Step 2 needs to add a key value and add elements, and step 2 uses the set to achieve de-duplication, however, the set must be converted to a 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
Output result:
{'C': [1, 2, 3, 4]}
However, in batch processing, there may be only one key value element, which causes the compiler to recognize as int type and cause 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 solution is to manually 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
In this way, it can run normally. Here we use set to remove the features of repeated elements and add the same elements. However, if the element in 'B' is null, this method will also become invalid. Here, we need to take advantage of the nature of the last element in the python list that can be followed by a comma 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 cases.
The above example of Python merging dictionary key values and removing repeated elements is all the content shared by Alibaba Cloud. I hope you can give us a reference and support for the customer's house.