Python program to divide dictionary and its keys into K equal dictionaries
Last Updated :
13 Apr, 2023
Given a dictionary, divide it into an equal dictionary list of size k, by dividing each key’s value.
Input : test_dict = {“Gfg” : 9, “is” : 6, “best” : 12} , K = 3
Output : [{‘Gfg’: 3.0, ‘is’: 2.0, ‘best’: 4.0}, {‘Gfg’: 3.0, ‘is’: 2.0, ‘best’: 4.0}, {‘Gfg’: 3.0, ‘is’: 2.0, ‘best’: 4.0}]
Explanation : Values distributed equally among dictionaries.
Input : test_dict = {“Gfg” : 6, “is” : 4, “best” : 2} , K = 2
Output : [{‘Gfg’: 3.0, ‘is’: 2.0, ‘best’: 1.0}, {‘Gfg’: 3.0, ‘is’: 2.0, ‘best’: 1.0}]
Explanation : Values distributed equally among dictionaries.
Method #1: Using loop
This is one of the ways in which this task can be performed. In this, we compute each required key’s value and append each dictionary into the dictionaries list.
Python3
test_dict = { "Gfg" : 20 , "is" : 36 , "best" : 100 }
print ( "The original dictionary is : " + str (test_dict))
K = 4
temp = dict ()
for key in test_dict:
temp[key] = test_dict[key] / 4
res = []
for idx in range (K):
res.append(temp)
print ( "Required dictionary list : " + str (res))
|
Output:
The original dictionary is : {‘Gfg’: 20, ‘is’: 36, ‘best’: 100}
Required dictionary list : [{‘Gfg’: 5.0, ‘is’: 9.0, ‘best’: 25.0}, {‘Gfg’: 5.0, ‘is’: 9.0, ‘best’: 25.0}, {‘Gfg’: 5.0, ‘is’: 9.0, ‘best’: 25.0}, {‘Gfg’: 5.0, ‘is’: 9.0, ‘best’: 25.0}]
Method #2 : Using dictionary comprehension + list comprehension
This is yet another way in which this task can be performed. In this, we form dictionary using dictionary comprehension and list using list comprehension as a shorthand to solve this problem.
Python3
def divideDictKeys(dictionary, K):
temp = {key: test_dict[key] / K for key in test_dict}
res = [temp for idx in range (K)]
return str (res)
test_dict = { "Gfg" : 20 , "is" : 36 , "best" : 100 }
K = 4
print ( "The original dictionary is : " + str (test_dict))
print ( "Required dictionary list : " + divideDictKeys(test_dict, K))
|
Output:
The original dictionary is : {‘Gfg’: 20, ‘is’: 36, ‘best’: 100}
Required dictionary list : [{‘Gfg’: 5.0, ‘is’: 9.0, ‘best’: 25.0}, {‘Gfg’: 5.0, ‘is’: 9.0, ‘best’: 25.0}, {‘Gfg’: 5.0, ‘is’: 9.0, ‘best’: 25.0}, {‘Gfg’: 5.0, ‘is’: 9.0, ‘best’: 25.0}]
The time complexity of this approach is O(n), where n is the size of the dictionary.
The space complexity of this approach is O(n*K), as it creates K new dictionaries of size n/K each.
Share your thoughts in the comments
Please Login to comment...