Open In App

Convert String Dictionary to Dictionary Python

Last Updated : 24 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Interconversions of data types have been discussed many times and have been quite a popular problem to solve. This article discusses yet another problem of interconversion of the dictionary, in string format to a dictionary. Let’s discuss certain ways in which this can be done.

Convert String Dictionary to Dictionary Using json.loads() 

This task can easily be performed using the inbuilt function of loads of json library of python which converts the string of valid dictionary into json form, dictionary in Python. 

Step-by-step approach:

  1. Import the ‘json‘ module.
  2. Initialize a string variable ‘test_string’ with a dictionary in string format.
  3. Print the original string using the ‘print()’ function and concatenating it with the ‘test_string’ variable converted to a string using the ‘str()’ function.
  4. Use the ‘json.loads()’ function to convert the dictionary string to a dictionary object and assign it to the variable ‘res’.
  5. Print the converted dictionary using the ‘print()’ function and concatenating it with the ‘res’ variable converted to a string using the ‘str()’ function.

Python3




# Python3 code to demonstrate
# convert dictionary string to dictionary
# using json.loads()
import json
 
# initializing string
test_string = '{"Nikhil" : 1, "Akshat" : 2, "Akash" : 3}'
 
# printing original string
print("The original string : " + str(test_string))
 
# using json.loads()
# convert dictionary string to dictionary
res = json.loads(test_string)
 
# print result
print("The converted dictionary : " + str(res))


Output : 

The original string : {"Nikhil" : 1, "Akshat" : 2, "Akash" : 3}
The converted dictionary : {'Nikhil': 1, 'Akshat': 2, 'Akash': 3}

Time complexity: O(1) as it’s a single function call to json.loads that takes a string as input and returns a dictionary.
Auxiliary space: O(n), where n is the length of the input string. This is because the returned dictionary takes space proportional to the length of the input string.

Using ast.literal_eval() to Convert String Dictionary to Dictionary

The above method can also be used to perform a similar conversion. Function safer than the eval function and can be used for interconversion of all data types other than dictionary as well. 

 steps :

  1. The program imports the ast module.
  2. The program initializes a string variable test_string with a string representation of a dictionary: {“Nikhil” : 1, “Akshat” : 2, “Akash” : 3}.
  3. The program prints the original string using the print() function and the str() function to convert the test_string variable to a string: print(“The original string : ” + str(test_string)).
  4. The program uses the ast.literal_eval() function to convert the string representation of the dictionary into a Python dictionary: res = ast.literal_eval(test_string).
  5. The program prints the resulting dictionary using the print() function and the str() function to convert the res variable to a string: print(“The converted dictionary : ” + str(res)).

Python3




# Python3 code to demonstrate
# convert dictionary string to dictionary
# using ast.literal_eval()
import ast
 
# initializing string
test_string = '{"Nikhil" : 1, "Akshat" : 2, "Akash" : 3}'
 
# printing original string
print("The original string : " + str(test_string))
 
# using ast.literal_eval()
# convert dictionary string to dictionary
res = ast.literal_eval(test_string)
 
# print result
print("The converted dictionary : " + str(res))


Output : 

The original string : {"Nikhil" : 1, "Akshat" : 2, "Akash" : 3}
The converted dictionary : {'Nikhil': 1, 'Akshat': 2, 'Akash': 3}

Time complexity: O(n) where n is the number of characters in the dictionary string.
Auxiliary space: O(n) where n is the number of elements in the dictionary string.

Convert String Dictionary to Dictionary Using eval() 

The above method can also be used to perform a similar conversion. The eval() function parse the argument passed and converts it to a python expression and runs the python expression.

Python




# Python3 code to demonstrate
# convert dictionary string to dictionary
# using eval()
 
# initializing string
test_string = '{"Nikhil" : 1, "Akshat" : 2, "Akash" : 3}'
 
# printing original string
print("The original string : " + str(test_string))
 
# using eval()
# convert dictionary string to dictionary
res = eval(test_string)
 
# print result
print("The converted dictionary : " + str(res))


Output:

The original string : {"Nikhil" : 1, "Akshat" : 2, "Akash" : 3}
The converted dictionary : {'Nikhil': 1, 'Akshat': 2, 'Akash': 3}

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

Convert String Dictionary to Dictionary Using the split() method and a dictionary comprehension

First, we remove the curly braces from the string using the strip() method. Then, we split the string into a list of key-value pairs using the split() method. Finally, we use dictionary comprehension to iterate over the pairs, split them into separate key and value strings, and convert the values to integers before adding them to the dictionary. The resulting dictionary is returned.

Python3




def str_to_dict(string):
    # remove the curly braces from the string
    string = string.strip('{}')
 
    # split the string into key-value pairs
    pairs = string.split(', ')
 
    # use a dictionary comprehension to create
    # the dictionary, converting the values to
    # integers and removing the quotes from the keys
    return {key[1:-2]: int(value) for key, value in (pair.split(': ') for pair in pairs)}
 
 
# test the function
test_string = '{"Nikhil" : 1, "Akshat" : 2, "Akash" : 3}'
print("The original string : " + str(test_string))
print("The converted dictionary : " + str(
    str_to_dict(test_string)))  # The original string : {"Nikhil" : 1, "Akshat" : 2, "Akash" : 3}
# The converted dictionary : {'Nikhil': 1, 'Akshat': 2, 'Akash': 3}


Output

The original string : {"Nikhil" : 1, "Akshat" : 2, "Akash" : 3}
The converted dictionary : {'Nikhil': 1, 'Akshat': 2, 'Akash': 3}

Time Complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n)

Convert String Dictionary to Dictionary Using the eval() function along with a replace() function

  • Initialize a string containing the dictionary in string format.
  • Use the replace() function to replace all the single quotes (‘) in the string with double quotes (“).
  • Use the eval() function to evaluate the resulting string as a Python expression, which will be a dictionary object.
  • Assign the resulting dictionary to a variable.

Python3




# Python3 code to demonstrate
# convert dictionary string to dictionary
# using eval() and replace()
 
# initializing string
test_string = "{'Nikhil' : 1, 'Akshat' : 2, 'Akash' : 3}"
 
# printing original string
print("The original string : " + str(test_string))
 
# using eval() and replace()
# convert dictionary string to dictionary
res = eval(test_string.replace("'", "\""))
 
# print result
print("The converted dictionary : " + str(res))


Output

The original string : {'Nikhil' : 1, 'Akshat' : 2, 'Akash' : 3}
The converted dictionary : {'Nikhil': 1, 'Akshat': 2, 'Akash': 3}

Time complexity: O(n), where n is the length of the input string. This is because the replace() function has a time complexity of O(n).
Auxiliary space: O(n), where n is the length of the input string.



Similar Reads

Python | Convert flattened dictionary into nested dictionary
Given a flattened dictionary, the task is to convert that dictionary into a nested dictionary where keys are needed to be split at '_' considering where nested dictionary will be started. Method #1: Using Naive Approach Step-by-step approach : Define a function named insert that takes two parameters, a dictionary (dct) and a list (lst). This functi
8 min read
Python | Convert nested dictionary into flattened dictionary
Given a nested dictionary, the task is to convert this dictionary into a flattened dictionary where the key is separated by '_' in case of the nested key to be started. Method #1: Using Naive Approach Step-by-step approach : The function checks if the input dd is a dictionary. If it is, then it iterates over each key-value pair in the dictionary, a
8 min read
Convert Dictionary Value list to Dictionary List Python
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Input : test_list =
9 min read
Python | Convert dictionary object into string
The dictionary is an important container and is used almost in every code of day-to-day programming as well as web development with Python. The more it is used, the more is the requirement to master it and hence it's necessary to learn about them. Input: { "testname" : "akshat","test2name" : "manjeet","test3name" : "nikhil"}Output: {"testname": "ak
3 min read
Python | Convert byteString key:value pair of dictionary to String
Given a dictionary having key:value pairs as byteString, the task is to convert the key:value pair to string. Examples: Input: {b'EmplId': b'12345', b'Name': b'Paras', b'Company': b'Cyware' } Output: {'EmplId': '12345', 'Name': 'Paras', 'Company': 'Cyware'} Input: {b'Key1': b'Geeks', b'Key2': b'For', b'Key3': b'Geek' } Output: {'Key1':'Geeks', 'Key
4 min read
Python | Convert key-value pair comma separated string into dictionary
Given a string, with different key-value pairs separated with commas, the task is to convert that string into the dictionary. These types of problems are common in web development where we fetch arguments from queries or get a response in the form of strings. Given below are a few methods to solve the task. Method #1: Using dictionary comprehension
5 min read
Python - Convert Dictionary to Concatenated String
Sometimes, while working with Dictionaries, we can have a task in which we need to perform the conversion of converting dictionary to string, which is concatenated key-value pair. This can have application in domains in which we require to reduce storage space or require strings as target data. Let's discuss certain ways in which this task can be p
6 min read
Python - Convert key-value String to dictionary
Sometimes, while working with Python strings, we can have problems in which we need to convert a string's key-value pairs to the dictionary. This can have applications in which we are working with string data that needs to be converted. Let's discuss certain ways in which this task can be performed. Method #1 : Using map() + split() + loop The comb
4 min read
Python - Convert String List to Key-Value List dictionary
Given a string, convert it to key-value list dictionary, with key as 1st word and rest words as value list. Input : test_list = ["gfg is best for geeks", "CS is best subject"] Output : {'gfg': ['is', 'best', 'for', 'geeks'], 'CS': ['is', 'best', 'subject']} Explanation : 1st elements are paired with respective rest of words as list. Input : test_li
8 min read
Python program to split the string and convert it to dictionary
Given a delimiter (denoted as delim in code) separated string, order the splits in form of dictionary. Examples: Input : test_str = 'gfg*is*best*for*geeks', delim = “*” Output : {0: 'gfg', 1: 'is', 2: 'best', 3: 'for', 4: 'geeks'} Input : test_str = 'gfg*is*best', delim = “*” Output : {0: 'gfg', 1: 'is', 2: 'best'} Method 1 : Using split() + loop T
4 min read
Practice Tags :