Python | Union of Value Lists
Last Updated :
22 Apr, 2023
The functionality of union has been discussed many times. But sometimes, we can have a more complex container, in which we need to check for the union of lists which are in form of keys of dictionary. Let's discuss certain ways to solve this type of problem.
Method #1 : Using Loops Using loops is a naive brute force approach to perform this particular task. In this method, we check for keys present in both list and check for non-repeating values to add to result. We even check for the keys completely not present in other to add its whole list value.
Python3
# Python3 code to demonstrate
# Union of Value Lists
# using loops
# initializing dicts
test_dict1 = { "Key1" : [1, 3, 4], "key2" : [4, 5] }
test_dict2 = { "Key1" : [1, 7, 8] }
# printing original dicts
print("The original dict 1 : " + str(test_dict1))
print("The original dict 2 : " + str(test_dict2))
# using loops
# Union of Value Lists
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]}
Time Complexity: O(m*n) where m and n is the number of elements in the dictioneries “test_dict 1” and “test_dict 1” respectively. loops performs m*n number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list
Method #2 : Using dictionary comprehension + set operations This is the one line approach to solve the similar problem and offers a compact alternative to above method. This solution processes by using the set comprehension to get the necessary elements bound together into lists using dictionary comprehension.
Python3
# Python3 code to demonstrate
# Union of Value Lists
# using dictionary comprehension + set operations
# initializing dicts
test_dict1 = { "Key1" : [1, 3, 4], "key2" : [4, 5] }
test_dict2 = { "Key1" : [1, 7, 8] }
# printing original dicts
print("The original dict 1 : " + str(test_dict1))
print("The original dict 2 : " + str(test_dict2))
# using dictionary comprehension + set operations
# Union of Value Lists
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))
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#3: Using the set union operator |
Approach
the set union operator | to take the union of corresponding value lists for keys that exist in both input dictionaries. It then adds the key-value pairs to the new dictionary and adds the remaining key-value pairs from each input dictionary to the new dictionary. This approach has a time and space complexity of O(n), where n is the total number of keys in both input dictionaries.
Algorithm
1. Create a new dictionary to hold the union of the two input dictionaries.
2. For each key that exists in both dictionaries, take the union of the corresponding value lists using the set union operator.
3. Add the key-value pairs to the new dictionary.
4. Add the key-value pairs from the first dictionary that do not exist in the second dictionary to the new dictionary.
5. Add the key-value pairs from the second dictionary that do not exist in the first dictionary to the new dictionary.
6. Return the new dictionary.
Python3
def union_of_value_lists_2(dict1, dict2):
result_dict = {}
for key in dict1.keys() & dict2.keys():
result_dict[key] = list(set(dict1[key]) | set(dict2[key]))
for key in dict1.keys() - dict2.keys():
result_dict[key] = dict1[key]
for key in dict2.keys() - dict1.keys():
result_dict[key] = dict2[key]
return result_dict
dict1 = { "Key1" : [1, 3, 4], "key2" : [4, 5] }
dict2 = { "Key1" : [1, 7, 8] }
print(union_of_value_lists_2(dict1, dict2))
Output{'Key1': [1, 3, 4, 7, 8], 'key2': [4, 5]}
Time complexity: O(n), where n is the total number of keys in both dictionaries.
Auxiliary Space: O(n), where n is the total number of keys in both dictionaries.
METHOD: Using dictionary unpacking and list concatenation.
APPROACH:
In this approach, we first merge the two dictionaries using the dictionary unpacking operator **. Then, we iterate over the keys and values of the merged dictionary and use the dictionary get() method to extract the corresponding lists from dict1 and dict2. We concatenate the lists using the + operator and remove any duplicates using the set() function. Finally, we convert the set back to a list and store the merged list in the corresponding key-value pair of the merged dictionary.
ALGORITHM:
1.Initialize two dictionaries dict1 and dict2 with the given key-value pairs.
2.Merge the two dictionaries using the dictionary unpacking operator **.
3.Iterate over the keys and values of the merged dictionary.
4.Use the dictionary get() method
Python3
dict1 = {'Key1': [1, 3, 4], 'key2': [4, 5]}
dict2 = {'Key1': [1, 7, 8]}
merged_dict = {**dict1, **dict2}
for key, value in merged_dict.items():
merged_dict[key] = list(set(dict1.get(key, []) + dict2.get(key, [])))
print(merged_dict)
Output{'Key1': [1, 3, 4, 7, 8], 'key2': [4, 5]}
Time complexity: O(m * n), where m and n are the number of keys in dict1 and dict2, respectively.
Auxiliary Space: O(m + n), where m and n are the number of keys in dict1 and dict2, respectively.
Method: Using defaultdict
step-by-step algorithm
- Import defaultdict module from collections
- Define two dictionaries: test_dict1 and test_dict2
- Create an empty result_dict using defaultdict()
- Iterate over the union of keys in test_dict1 and test_dict2 using set() and union operator
- Access the value list for each key in test_dict1 and test_dict2 using get() method and set default to empty list
- Concatenate the two value lists for the current key using the + operator
- Convert the concatenated list to a set to eliminate duplicates and then back to a list
- Assign the resulting list as the value for the current key in the result_dict using defaultdict()
- Print the final result_dict
Python3
from collections import defaultdict
# initializing dicts
test_dict1 = { "Key1" : [1, 3, 4], "key2" : [4, 5] }
test_dict2 = { "Key1" : [1, 7, 8] }
# combine dictionaries and union value lists
result_dict = defaultdict(list)
for key in set(test_dict1.keys()) | set(test_dict2.keys()):
result_dict[key] = sorted(list(set(test_dict1.get(key, []) + test_dict2.get(key, []))))
# print result as sorted dict
print("The dicts after union is : " + str(dict(sorted(result_dict.items()))))
Time Complexity: O(n) where n is the total number of values in both dictionaries. This is because the algorithm needs to iterate over all the keys and values in both dictionaries and perform set operations and concatenations.
Auxiliary Space Complexity: O(n) where n is the total number of values in both dictionaries. This is because the algorithm creates a new dictionary to store the union of the value lists and uses sets to eliminate duplicates, both of which require additional memory. However, the use of defaultdict() ensures that the resulting dictionary only contains keys that were present in either test_dict1 or test_dict2, so the actual space used may be less than the total number of values in both dictionaries.
Method: Using reduce():
- Import reduce method from the functools module.
- Initialize two dictionaries test_dict1 and test_dict2.
- Create a lambda function to combine the dictionaries and union the value lists.
- Use reduce() method to combine the two dictionaries and union the value lists.
- Print the result.
Python3
from functools import reduce
# initializing dicts
test_dict1 = {"Key1": [1, 3, 4], "key2": [4, 5]}
test_dict2 = {"Key1": [1, 7, 8]}
# Print original dicts
print("The original dict 1 : " + str(test_dict1))
print("The original dict 2 : " + str(test_dict2))
# combine dictionaries and union value
# lists using reduce() method
result_dict = reduce(lambda x, y: {k: sorted(list(set(x.get(
k, []) + y.get(k, [])))) for k in s
et(x) | set(y)}, [test_dict1, test_dict2])
# print result as sorted dict
print("The dicts after union is : " + str(dict(sorted(result_dict.items()))))
OutputThe 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, 3, 4, 7, 8], 'key2': [4, 5]}
Time Complexity: The time complexity of this code is O(n log n), where n is the length of the input dictionary.
Space Complexity: The space complexity of this code is O(n), where n is the length of the input dictionary.
Similar Reads
Python | Summation of tuples in list
Sometimes, while working with records, we can have a problem in which we need to find the cumulative sum of all the values that are present in tuples. This can have applications in cases in which we deal with a lot of record data. Let's discuss certain ways in which this problem can be solved. Metho
7 min read
Sort Tuple of Lists in Python
The task of sorting a tuple of lists involves iterating through each list inside the tuple and sorting its elements. Since tuples are immutable, we cannot modify them directly, so we must create a new tuple containing the sorted lists. For example, given a tuple of lists a = ([2, 1, 5], [1, 5, 7], [
3 min read
Python | Unpacking tuple of lists
Given a tuple of lists, write a Python program to unpack the elements of the lists that are packed inside the given tuple. Examples: Input : (['a', 'apple'], ['b', 'ball']) Output : ['a', 'apple', 'b', 'ball'] Input : ([1, 'sam', 75], [2, 'bob', 39], [3, 'Kate', 87]) Output : [1, 'sam', 75, 2, 'bob'
3 min read
Python | Summation of two list of tuples
Sometimes, while working with Python records, we can have a problem in which we need to perform cross-summation of list of tuples. This kind of application is popular in web development domain. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + zip
6 min read
Python | Grouped summation of tuple list
Many times, we are given a list of tuples and we need to group its keys and perform certain operations while grouping. The most common operation is addition. Let's discuss certain ways in which this task can be performed. Apart from addition, other operations can also be performed by doing small cha
10 min read
Python - Add Values to Dictionary of List
A dictionary of lists allows storing grouped values under specific keys. For example, in a = {'x': [10, 20]}, the key 'x' maps to the list [10, 20]. To add values like 30 to this list, we use efficient methods to update the dictionary dynamically. Letâs look at some commonly used methods to efficien
3 min read
Python - Minimum in tuple list value
Many times, while dealing with containers in any language we come across lists of tuples in different forms, tuples in themselves can have sometimes more than native datatypes and can have list as their attributes. This article talks about the minimum of list as tuple attribute. Letâs discuss certai
5 min read
Python | Merge Python key values to list
Sometimes, while working with Python, we might have a problem in which we need to get the values of dictionary from several dictionaries to be encapsulated into one dictionary. This type of problem can be common in domains in which we work with relational data like in web developments. Let's discuss
4 min read
Python | List of tuples Minimum
Sometimes, while working with Python records, we can have a problem in which we need to perform cross minimum of list of tuples. This kind of application is popular in web development domain. Letâs discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + zip()
4 min read
Min and Max value in list of tuples-Python
The task of finding the minimum and maximum values in a list of tuples in Python involves identifying the smallest and largest elements from each position (column) within the tuples. For example, given [(2, 3), (4, 7), (8, 11), (3, 6)], the first elements (2, 4, 8, 3) have a minimum of 2 and a maxim
3 min read