Python - Convert dictionary to K sized dictionaries
Last Updated :
27 Apr, 2023
Given a Dictionary, divide dictionary into K sized different dictionaries list.
Input : test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'geeks' : 5, 'CS' : 6}, K = 3
Output : [{'Gfg': 1, 'is': 2, 'best': 3}, {'for': 4, 'geeks': 5, 'CS': 6}]
Explanation : Divided into size of 3 keys.
Input : test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4}, K = 2
Output : [{'Gfg': 1, 'is': 2}, {'best': 3, 'for': 4}]
Explanation : Divided into size of 2 keys.
Method 1: Using loop
In this, we iterate for all the keys in dictionary using loop and bifurcate according to size and append to new list.
Python3
# Python3 code to demonstrate working of
# Convert dictionary to K Keys dictionaries
# Using loop
# initializing dictionary
test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'geeks' : 5, 'CS' : 6}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = 2
res = []
count = 0
flag = 0
indict = dict()
for key in test_dict:
indict[key] = test_dict[key]
count += 1
# checking for K size and avoiding empty dict using flag
if count % K == 0 and flag:
res.append(indict)
# reinitializing dictionary
indict = dict()
count = 0
flag = 1
# printing result
print("The converted list : " + str(res))
OutputThe original dictionary is : {'Gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'geeks': 5, 'CS': 6}
The converted list : [{'Gfg': 1, 'is': 2}, {'best': 3, 'for': 4}, {'geeks': 5, 'CS': 6}]
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 dictionary comprehension
Step-by-step approach:
- Initialize a dictionary called test_dict with key-value pairs.
- Print the original dictionary using the print() function.
- Set the value of K to the desired number of keys per dictionary.
- Use dictionary comprehension to create a list of dictionaries. Inside the comprehension, iterate over the items of test_dict and use the modulo operator to group them into sub-dictionaries of size K. The dict() constructor is used to create each sub-dictionary.
- Print the resulting list of dictionaries using the print() function.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Convert dictionary to K Keys dictionaries
# Using dictionary comprehension
# initializing dictionary
test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'geeks' : 5, 'CS' : 6}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = 2
# using dictionary comprehension to create list of sub-dictionaries
res = [dict(list(test_dict.items())[i:i+K]) for i in range(0, len(test_dict), K)]
# printing result
print("The converted list : " + str(res))
OutputThe original dictionary is : {'Gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'geeks': 5, 'CS': 6}
The converted list : [{'Gfg': 1, 'is': 2}, {'best': 3, 'for': 4}, {'geeks': 5, 'CS': 6}]
Time complexity: O(N), where N is the number of key-value pairs in the original dictionary.
Auxiliary space: O(N/K), where N is the number of key-value pairs in the original dictionary and K is the size of each sub-dictionary.
Method 3: Using the iter function and the dict constructor.
Step-by-step approach:
- Initialize an empty list to store the sub-dictionaries.
- Get an iterator of the original dictionary using the iter function.
- In each iteration, use the dict constructor to create a sub-dictionary from the next K items in the iterator, where K is the desired number of keys in each sub-dictionary.
- Append the sub-dictionary to the list of sub-dictionaries.
- Return the list of sub-dictionaries.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Convert dictionary to K Keys dictionaries
# Using iter function and dict constructor
import itertools
# initializing dictionary
test_dict = {'Gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'geeks': 5, 'CS': 6}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = 2
# using iter function and dict constructor to create list of sub-dictionaries
it = iter(test_dict.items())
res = []
while True:
sub_dict = dict(itertools.islice(it, K))
if not sub_dict:
break
res.append(sub_dict)
# printing result
print("The converted list : " + str(res))
OutputThe original dictionary is : {'Gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'geeks': 5, 'CS': 6}
The converted list : [{'Gfg': 1, 'is': 2}, {'best': 3, 'for': 4}, {'geeks': 5, 'CS': 6}]
Time complexity: O(n), where n is the number of items in the original dictionary.
Auxiliary space: O(n), since we need to store the list of sub-dictionaries.
Similar Reads
Python - Convert Flat dictionaries to Nested dictionary Sometimes, while working with records, we can have a problem in which we need to perform the task of conversion of multiple flat dictionaries to a single nested dictionary. This can have applications in many domains in which data is used extensively. Let's discuss certain ways by which we can conver
4 min read
Python - Convert Flat dictionaries to Nested dictionary Sometimes, while working with records, we can have a problem in which we need to perform the task of conversion of multiple flat dictionaries to a single nested dictionary. This can have applications in many domains in which data is used extensively. Let's discuss certain ways by which we can conver
4 min read
Python - Convert list of dictionaries to Dictionary Value list We are given a list of dictionaries we need to convert it to dictionary. For example, given a list of dictionaries: d = [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}, {'a': 5, 'b': 6}], the output should be: {'a': [1, 3, 5], 'b': [2, 4, 6]}.Using Dictionary ComprehensionUsing dictionary comprehension, we can
3 min read
Convert Dictionary of Dictionaries to Python List of Dictionaries We are given dictionary of dictionaries we need to convert it to list of dictionaries. For example, For example, we are having d = { 'A': {'color': 'red', 'shape': 'circle'}, 'B': {'color': 'blue', 'shape': 'square'}, 'C': {'color': 'green', 'shape': 'triangle'} } we need to convert it to a list of
2 min read
Convert Dictionary to String List in Python The task of converting a dictionary to a string list in Python involves transforming the key-value pairs of the dictionary into a formatted string and storing those strings in a list. For example, consider a dictionary d = {1: 'Mercedes', 2: 'Audi', 3: 'Porsche', 4: 'Lambo'}. Converting this to a st
3 min read
Convert List of Lists to Dictionary - Python We are given list of lists we need to convert it to python . For example we are given a list of lists a = [["a", 1], ["b", 2], ["c", 3]] we need to convert the list in dictionary so that the output becomes {'a': 1, 'b': 2, 'c': 3}. Using Dictionary ComprehensionUsing dictionary comprehension, we ite
3 min read