Open In App

Python – Convert String to Nested Dictionaries

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with dictionaries, we can have a problem in which we need to convert a String to nested dictionary, each separator occurrence meaning a new nesting. This is a particular problem but can occur in data domains and day-day programming. Let’s discuss certain way in which this task can be done. 

Method : Using loop + recursion This is way in which this task can be performed. In this, we recur for nesting of dictionary as we encounter a separator occurrence. 

Python3
# Python3 code to demonstrate working of 
# Convert String to Nested Dictionaries
# Using loop

def helper_fnc(test_str, sep):
  if sep not in test_str:
    return test_str
  key, val = test_str.split(sep, 1)
  return {key: helper_fnc(val, sep)}

# initializing string
test_str = 'gfg_is_best_for_geeks'

# printing original string
print("The original string is : " + str(test_str))

# initializing separator
sep = '_'

# Convert String to Nested Dictionaries
# Using loop
res = helper_fnc(test_str, sep)

# printing result 
print("The nested dictionary is : " + str(res)) 

Output
The original string is : gfg_is_best_for_geeks
The nested dictionary is : {'gfg': {'is': {'best': {'for': 'geeks'}}}}



Using a Stack:

Approach:

We can also convert the string to a nested dictionary using a stack. We will split the string into a list of keys and use a stack to keep track of the current dictionary. We will iterate through the list of keys and push each key onto the stack. If the next key is the last key, we will set the value of the current dictionary to the last key. Otherwise, we will create a new dictionary and set the value of the current dictionary to the new dictionary. We will then push the new dictionary onto the stack and make it the current dictionary.

Python3
def convert_to_dict(string):
    keys = string.split('_')
    stack = []
    current_dict = {}
    for key in keys:
        if len(stack) == len(keys) - 1:
            stack[-1][prev_key] = key
        else:
            new_dict = {}
            current_dict[key] = new_dict
            stack.append(current_dict)
            current_dict = new_dict
            prev_key = key
    return stack[0]


string = 'gfg_is_best_for_geeks'
result = convert_to_dict(string)
print(result)

Output
{'gfg': {'is': {'best': {'for': 'geeks'}}}}



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


Last Updated : 14 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads