  # Python | Union of lists of values

Loops | Python Methods and Functions | String Variables

Method # 1: Using Loops
Using loops is a naive crude method for this particular task. In this method, we check for the presence of keys in both lists and check for non-duplicate values ​​to add to the result. We even check for keys not found in others to add the value of the entire list.

 ` # Python3 demo code ` ` # Union of lists of values ​​` ` # using loops `   ` # dict initialization ` ` test_dict1 ` ` = ` ` {` ` "Key1" ` `: [` ` 1 ` `, ` ` 3 ` `, ` ` 4 ` `], ` ` "key2" ` `: [` ` 4 ` `, ` ` 5 ` `]} `` test_dict2 = { "Key1" : [ 1 , 7 , 8 ]}   # printing original dictations print ( "The original dict 1:" + str (test_dict1)) print ( "The original dict 2:" + str (test_dict2))   # use Using loops # Union of lists of values ​​ for key in test_dict1:  if key in test_dict2:    for val in test_dict1 [key]:   if val not in test_dict2 [key]:    test_dict2 [key] .append (val)   else :    test_dict2 [key] = test_dict1 [key] [:]    # print result print ( "The dicts after union is:" + str (test_dict2)) `

Output:

` The original dict 1: {`Key1`: [1, 3, 4],` key2`: [4, 5]} The original dict 2: {`Key1`: [1, 7, 8]} The dicts after union is: {`Key1`: [1, 7, 8, 3, 4],` key2`: [4, 5]} `

Method # 2: Using dictionary comprehension + typing operation
This is a one-line approach to solve a similar problem, offering a compact alternative to the above method. This solution is handled using the given comprehension to combine the required elements into lists using dictionary comprehension.

 ` # Python3 demo code ` ` # Union of lists of values ​​` ` # using dictionary comprehension + set operations `   ` # dict initialization ` ` test_dict1 ` ` = ` ` {` ` "Key1" ` `: [ ` ` 1 ` `, ` ` 3 ` `, ` ` 4 ` `], ` ` "key2" ` `: [` ` 4 ` `, ` ` 5 ` `]} `` test_dict2 = { "Key1" : [ 1 , 7 , 8 ] }   # printing original dictations print ( "The original dict 1:" + str (test_dict1)) print ( "The original dict 2:" + str  (test_dict2))   # using dictionary comprehension + operations on sets # Union of lists of values ​​ res = {key: list ( set (test_dict1.get (key, []) + test_dict2.get (key, [])))    for key in set (test_dict2) |  set (test_dict1)}   # print result print ( "The dicts after union is:" + str (res)) `

Exit:

` The original dict 1: {`Key1`: [1, 3, 4],` key2`: [4, 5]} The original dict 2: {`Key1`: [1 , 7, 8]} The dicts after union is: {`Key1`: [1, 7, 8, 3, 4],` key2`: [4, 5]} `