Open In App

Python | Equal Keys List Summation

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with dictionaries, we can have a problem in which we have many dictionaries and we are required to sum like keys. This problem seems common, but complex is if the values of keys are list and we need to add elements to list of like keys. Let’s discuss way in which this problem can be solved. 

Method : Using list comprehension + items() + sum() This problem can be solved using list comprehension and sum() that can be used to sum the list content and also the items method which can be employed to get the dictionary keys and values. 

Python3




# Python3 code to demonstrate working of
# Equal Keys List Summation
# Using items() + list comprehension + sum()
 
# initializing dictionaries
test_dict1 = {'Gfg' : [1, 2, 3], 'for' : [2, 4], 'CS' : [7, 8]}
test_dict2 = {'Gfg' : [10, 11], 'for' : [5], 'CS' : [0, 18]}
 
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
 
# Using items() + list comprehension + sum()
# Equal Keys List Summation
res = {key: sum(value) + sum(test_dict2[key]) for key, value in test_dict1.items()}
 
# printing result
print("The summation of dictionary values is : " + str(res))


Output : 

The original dictionary 1 is : {'CS': [7, 8], 'for': [2, 4], 'Gfg': [1, 2, 3]}
The original dictionary 2 is : {'CS': [0, 18], 'for': [5], 'Gfg': [10, 11]}
The summation of dictionary values is : {'CS': 33, 'for': 11, 'Gfg': 27}

Time Complexity: O(n*n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list

Method#2 : Using for loop 

In this method, we first loop through the keys of the first dictionary, and for each key, we check if it exists in the second dictionary. If it does, we sum the values of the two lists using the + operator and store the result in the result_dict. If the key is not present in the second dictionary, we simply sum the values of the list from the first dictionary and store the result in the result_dict. Finally, we loop through the keys of the second dictionary, and for each key that is not already present in the result_dict, we sum the values of the list from the second dictionary and store the result in the result_dict

Python3




dict1 = {'CS': [7, 8], 'for': [2, 4], 'Gfg': [1, 2, 3]}#dictionary input 1
dict2 = {'CS': [0, 18], 'for': [5], 'Gfg': [10, 11]}#dictionary input 2
 
result_dict = {}#take empty dictionary
 
for key in dict1.keys():#using loop to get keys from dict1
    if key in dict2:
        result_dict[key] = sum(dict1[key] + dict2[key])#summation of keys
    else:
        result_dict[key] = sum(dict1[key])
 
for key in dict2.keys():#using loop to get keys from dict2
    if key not in result_dict:#summation of keys
        result_dict[key] = sum(dict2[key])
 
print("The summation of dictionary values is :", result_dict)#print result


Output

The summation of dictionary values is : {'CS': 33, 'for': 11, 'Gfg': 27}

Time complexity: O(n)
Auxiliary Space: O(n)

Method#3 : Using itertools.chain() and itertools.groupby():

Algorithm:

1. Import the necessary modules, itertools.
2.Define two dictionaries.
3.Create an empty dictionary.
4.Merge the keys of both the dictionaries using chain() function and group them using groupby() function.
5.Find the sum of values of common keys in both the dictionaries, using get() function.
6.Store the result in a new dictionary.
7.Print the new dictionary.

Python3




from itertools import chain, groupby
 
dict1 = {'CS': [7, 8], 'for': [2, 4], 'Gfg': [1, 2, 3]}
dict2 = {'CS': [0, 18], 'for': [5], 'Gfg': [10, 11]}
# printing original dictionaries
print("The original dictionary 1 is : " + str(dict1))
print("The original dictionary 2 is : " + str(dict2))
  
 
merged_dict = {}
for key, group in groupby(sorted(chain(dict1.keys(), dict2.keys()))):
    merged_dict[key] = sum(chain(dict1.get(key, []), dict2.get(key, [])))
 
print("The summation of dictionary values is :", merged_dict)
#This code is contributed by Jyothi pinjala.


Output

The original dictionary 1 is : {'CS': [7, 8], 'for': [2, 4], 'Gfg': [1, 2, 3]}
The original dictionary 2 is : {'CS': [0, 18], 'for': [5], 'Gfg': [10, 11]}
The summation of dictionary values is : {'CS': 33, 'Gfg': 27, 'for': 11}

Time Complexity: O(NlogN)

The use of sorted() function makes the time complexity O(NlogN).
The iteration over the merged keys has a time complexity of O(N), as does the iteration over the values of the dictionaries.
The sum() function has a time complexity of O(N).
Space Complexity: O(N)

We are using extra space for the merged dictionary which has the same number of elements as the input dictionaries. Therefore, the space complexity is O(N).



Last Updated : 27 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads