Open In App

Python – Split Dictionary values on size limit of values

Improve
Improve
Like Article
Like
Save
Share
Report

Given a dictionary with string values, the task is to write a python program to split values if the size of string exceeds K.

Input : {1 : “Geeksforgeeks”, 2 : “best for”, 3 : “all geeks”}, limit = 5
Output : {1: ‘Geeks’, 2: ‘forge’, 3: ‘eks’, 4: ‘best ‘, 5: ‘for’, 6: ‘all g’, 7: ‘eeks’}
Explanation : All string values are capped till length 5. New value is created post size limit.

Input : {1 : “Geeksforgeeks”, 2 : “best for”}, limit = 5
Output : {1: ‘Geeks’, 2: ‘forge’, 3: ‘eks’, 4: ‘best ‘, 5: ‘for’}
Explanation : All string values are capped till length 5. New value is created post size limit.

Method 1: Using dictionary comprehension + enumerate() + list slicing 

In this, we perform the task of getting required value chunks using list slicing and list comprehension on the iteration of values extracted using values(). The next step is to reassign keys with new chunked values using list comprehension and enumerate().

Python3




# Python3 code to demonstrate working of
# Split Dictionary values on size limit
# Using dictionary comprehension + enumerate() +  list slicing
 
# initializing dictionary
test_dict = {1: "Geeksforgeeks",
             2: "best for", 3:
             "all geeks"}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing limit
limit = 4
 
# cutting chunks of K
chunks = (sub[idx: idx + limit] for sub in test_dict.values()
          for idx in range(0, len(sub), limit))
 
# re assigning dictionary with chunks
res = {key: val for key, val in enumerate(chunks, 1)}
 
# printing result
print("The extracted values : " + str(res))


Output:

The original dictionary is : {1: ‘Geeksforgeeks’, 2: ‘best for’, 3: ‘all geeks’}

The extracted values : {1: ‘Geek’, 2: ‘sfor’, 3: ‘geek’, 4: ‘s’, 5: ‘best’, 6: ‘ for’, 7: ‘all ‘, 8: ‘geek’, 9: ‘s’}

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

Method 2: Using a for loop and string slicing

Step-by-step approach:

  • Initialize an empty dictionary called res.
  • Loop through each key-value pair in the test_dict.
  • For each value in the key-value pair, slice it into chunks of size limit using string slicing and store them in a temporary list called chunks.
  • Loop through each chunk in chunks, and add it as a value to the res dictionary with a new key that is incremented by 1 for each chunk.
  • Print the resulting dictionary res.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Split Dictionary values on size limit
# Using for loop and string slicing
 
# initializing dictionary
test_dict = {1: "Geeksforgeeks",
             2: "best for", 3:
             "all geeks"}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing limit
limit = 4
 
# initializing empty dictionary for result
res = {}
 
# loop through each key-value pair in test_dict
for key, value in test_dict.items():
    # split value into chunks of size limit using string slicing
    chunks = [value[i:i+limit] for i in range(0, len(value), limit)]
    # loop through each chunk and add it to res with a new key
    for i, chunk in enumerate(chunks):
        res[len(res)+1] = chunk
 
# printing result
print("The extracted values : " + str(res))


Output

The original dictionary is : {1: 'Geeksforgeeks', 2: 'best for', 3: 'all geeks'}
The extracted values : {1: 'Geek', 2: 'sfor', 3: 'geek', 4: 's', 5: 'best', 6: ' for', 7: 'all ', 8: 'geek', 9: 's'}

Time complexity: O(nm), where n is the number of key-value pairs in test_dict and m is the maximum length of any value in test_dict.
Auxiliary space: O(nm), since we are creating a new dictionary with the same number of key-value pairs as test_dict, and each value can be split into multiple chunks of size limit.

Method 3: Using a while loop and dictionary update

Step-by-step approach:

  • Initialize the original dictionary test_dict.
  • Print the original dictionary.
  • Initialize the size limit.
  • Create an empty dictionary res to store the result.
  • Loop over the items in the original dictionary using items().
  • Initialize the start index start to 0.
  • While the start index is less than the length of the value, do the following:
    a. Calculate the end index end for slicing by adding the limit to the start index.
    b. Slice the value using the start and end indices, and add the result to the result dictionary with a new key.
    c. Increment the start index by the limit.
  • Print the result dictionary.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Split Dictionary values on size limit
# Using while loop and dictionary update
 
# initializing dictionary
test_dict = {1: "Geeksforgeeks",
             2: "best for", 3:
             "all geeks"}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing limit
limit = 4
 
# create an empty dictionary to store the result
res = {}
 
# loop over the items in the original dictionary
for key, value in test_dict.items():
     
    # initialize the start index for slicing
    start = 0
     
    # split the value into chunks of size limit
    while start < len(value):
         
        # get the end index for slicing
        end = start + limit
         
        # slice the value and add it to the result dictionary
        res[len(res) + 1] = value[start:end]
         
        # increment the start index
        start = end
 
# printing result
print("The extracted values : " + str(res))


Output

The original dictionary is : {1: 'Geeksforgeeks', 2: 'best for', 3: 'all geeks'}
The extracted values : {1: 'Geek', 2: 'sfor', 3: 'geek', 4: 's', 5: 'best', 6: ' for', 7: 'all ', 8: 'geek', 9: 's'}

 Time complexity: O(n*m), where n is the number of values in the original dictionary and m is the maximum length of a value in the dictionary.
Auxiliary space: O(n*m), because we need to create a new dictionary to store the result, and the size of this dictionary is proportional to the number of values in the original dictionary and the maximum length of a value.

Method 4: Using list comprehension and dictionary update

Step-by-step approach:

  • Start by initializing the original dictionary and the size limit.
  • Create an empty dictionary to store the result.
  • Use list comprehension to split each value in the dictionary into chunks of size limit.
  • Loop over the items in the original dictionary, and use dictionary update to add each chunk as a new value to the result dictionary.
  • Print the result.

Below is the implementation of the above approach:

Python3




# initializing dictionary
test_dict = {1: "Geeksforgeeks",
             2: "best for", 3:
             "all geeks"}
 
# initializing limit
limit = 4
 
# create an empty dictionary to store the result
res = {}
 
# use list comprehension to split each value in the dictionary into chunks of size limit
chunks = [value[i:i+limit] for value in test_dict.values() for i in range(0, len(value), limit)]
 
# loop over the items in the original dictionary and use dictionary update to add each chunk as a new value to the result dictionary
for i, chunk in enumerate(chunks):
    res[i+1] = chunk
 
# printing result
print("The extracted values : " + str(res))


Output

The extracted values : {1: 'Geek', 2: 'sfor', 3: 'geek', 4: 's', 5: 'best', 6: ' for', 7: 'all ', 8: 'geek', 9: 's'}

Time complexity: O(nm), where n is the number of items in the dictionary and m is the length of the longest value in the dictionary.
Auxiliary space: O(nm), to store the chunks of each value in the list comprehension.

Method 5: Using built-in function divmod()

Step-by-step approach:

  • Initialize the original dictionary, test_dict.
  • Set the limit of each chunk, limit.
  • Initialize an empty dictionary to store the split chunks, res.
  • Loop through each key-value pair in test_dict.
  • Calculate the number of chunks needed to split the value, num_chunks, using divmod().
  • Split the value into num_chunks chunks using a list comprehension and string slicing, and store them in a list, chunks.
  • Loop through each chunk in chunks, and add it to res with a new key.
  • Return the res dictionary.

Python3




# Python3 code to demonstrate working of
# Split Dictionary values on size limit
# Using divmod() and list comprehension
 
# initializing dictionary
test_dict = {1: "Geeksforgeeks",
             2: "best for",
             3: "all geeks"}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing limit
limit = 4
 
# initializing empty dictionary for result
res = {}
 
# loop through each key-value pair in test_dict
for key, value in test_dict.items():
    # calculate the number of chunks needed to split the value
    num_chunks, remainder = divmod(len(value), limit)
    if remainder:
        num_chunks += 1
    # split value into chunks of size limit using string slicing
    chunks = [value[i:i+limit] for i in range(0, len(value), limit)]
    # loop through each chunk and add it to res with a new key
    for i, chunk in enumerate(chunks):
        res[len(res)+1] = chunk
 
# printing result
print("The extracted values : " + str(res))


Output

The original dictionary is : {1: 'Geeksforgeeks', 2: 'best for', 3: 'all geeks'}
The extracted values : {1: 'Geek', 2: 'sfor', 3: 'geek', 4: 's', 5: 'best', 6: ' for', 7: 'all ', 8: 'geek', 9: 's'}

Time complexity: O(n * m), where n is the number of key-value pairs in the test_dict dictionary and m is the maximum length of the value string. 
Auxiliary space: O(n * m), where n is the number of key-value pairs in the test_dict dictionary and m is the maximum length of the value string.



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