Python merges dictionary key values and removes instances of duplicate elements

  • 2020-05-19 05:05:37
  • OfStack

Suppose there is a 1 dictionary in python as follows:

x = {' a ':' 1, 2, 3 ', 'b' : '2 and 4'}

Need to be merged into:

x = {' c ':' 1, 2, 3, 4}

Three things need to be done:

1. Convert a string to a list of values
2. Merge the two lists and add new keys
3. Remove duplicate elements

The first step is accomplished by the commonly used function eval(). The second step requires adding a key value and adding elements. The third step USES the properties of the set collection to achieve the de-duplication effect. 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, there may be only one element with one key value, causing the compiler to recognize it as 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 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

This is done by artificially copying an element from 'b' so that the compiler does not recognize it 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

So it works. This takes advantage of the fact that set removes duplicate elements and adds the same ones. However, this method will also fail if the element in 'b' is empty. This takes advantage of the fact that the last element in the python list is allowed to be followed by a comma.


x={'a':'1,2,3','b':''}
x['c']=list(set(eval(x['a']+','+x['b'])))
del x['a']
del x['b']
print x

Operation results:

{'c': [1, 2, 3]}

The last one can handle the first two cases as well.


Related articles: