Python | Union of Value Lists

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

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

1. Import defaultdict module from collections
2. Define two dictionaries: test_dict1 and test_dict2
3. Create an empty result_dict using defaultdict()
4. Iterate over the union of keys in test_dict1 and test_dict2 using set() and union operator
5. Access the value list for each key in test_dict1 and test_dict2 using get() method and set default to empty list
6. Concatenate the two value lists for the current key using the + operator
7. Convert the concatenated list to a set to eliminate duplicates and then back to a list
8. Assign the resulting list as the value for the current key in the result_dict using defaultdict()
9. 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():

1. Import reduce method from the functools module.
2. Initialize two dictionaries test_dict1 and test_dict2.
3. Create a lambda function to combine the dictionaries and union the value lists.
4. Use reduce() method to combine the two dictionaries and union the value lists.
5. 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()))))`

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, 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.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Previous
Next