Skip to content
Related Articles
Open in App
Not now

Related Articles

Python – Merge keys by values

Improve Article
Save Article
Like Article
  • Last Updated : 29 Mar, 2023
Improve Article
Save Article
Like Article

Given a dictionary, merge the keys to map to common values.

Examples:

Input : test_dict = {1:6, 8:1, 9:3, 10:3, 12:6, 4:9, 2:3} 
Output : {‘1-12’: 6, ‘2-9-10’: 3, ‘4’: 9, ‘8’: 1} 
Explanation : All the similar valued keys merged.

Input : test_dict = {1:6, 8:1, 9:3, 4:9, 2:3} 
Output : {‘1’: 6, ‘2-9’: 3, ‘4’: 9, ‘8’: 1} 
Explanation : All the similar valued keys merged. 

Approach : Using defaultdict() + loop

This task is performed in 2 steps, first, group all the values and storing keys, and in 2nd step map merged keys to common values.

Python3




# Python3 code to demonstrate working of
# Merge keys by values
# Using defaultdict() + loop
from collections import defaultdict
 
# initializing dictionary
test_dict = {1: 6, 8: 1, 9: 3, 10: 3, 12: 6, 4: 9, 2: 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# grouping values
temp = defaultdict(list)
for key, val in sorted(test_dict.items()):
    temp[val].append(key)
 
res = dict()
# merge keys
for key in temp:
    res['-'.join([str(ele) for ele in temp[key]])] = key
 
# printing result
print("The required result : " + str(res))

Output:

The original dictionary is : {1: 6, 8: 1, 9: 3, 10: 3, 12: 6, 4: 9, 2: 3} 
The required result : {‘1-12’: 6, ‘2-9-10’: 3, ‘4’: 9, ‘8’: 1}

Using a dictionary to store the merged keys:

Approach:

Create an empty dictionary merged_dict to store the merged keys and values.
Loop through each key-value pair in the input dictionary test_dict.
Check if the value already exists in the merged_dict.
If the value does not exist, create a new key-value pair in the merged_dict with the value as the key and a list containing the key as the value.
If the value already exists, append the key to the list of keys corresponding to that value in the merged_dict.
Loop through each key in the merged_dict.
If the length of the list of keys corresponding to that value is 1, replace the list with the single key.
If the length of the list of keys corresponding to that value is greater than 1, sort the list of keys in ascending order, join them with a dash (‘-‘), and replace the list with the joined string.
Return the merged_dict.

Python3




def merge_keys(test_dict):
    merged_dict = {}
    for key, value in test_dict.items():
        if value not in merged_dict:
            merged_dict[value] = [key]
        else:
            merged_dict[value].append(key)
    for key in merged_dict:
        if len(merged_dict[key]) == 1:
            merged_dict[key] = merged_dict[key][0]
        else:
            merged_dict[key] = '-'.join([str(k) for k in sorted(merged_dict[key])])
    return merged_dict
test_dict1 = {1:6, 8:1, 9:3, 10:3, 12:6, 4:9, 2:3}
merged_dict1 = merge_keys(test_dict1)
print(merged_dict1)
 
test_dict2 = {1:6, 8:1, 9:3, 4:9, 2:3}
merged_dict2 = merge_keys(test_dict2)
print(merged_dict2)

Output

{6: '1-12', 1: 8, 3: '2-9-10', 9: 4}
{6: 1, 1: 8, 3: '2-9', 9: 4}

Time complexity: O(nlogn) due to sorting the merged keys

Auxiliary Space: O(n)


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!