Example code for using Python to merge dictionary key values ​​and remove duplicate elements

高洛峰
Release: 2017-03-24 17:32:37
Original
1844 people have browsed it

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
Copy after login


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
Copy after login


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
Copy after login


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
Copy after login


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
Copy after login


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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!