Change language

Python | Union of lists of values

| |

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]} 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically