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:
- Import the ‘json‘ module.
- Initialize a string variable ‘test_string’ with a dictionary in string format.
- Print the original string using the ‘print()’ function and concatenating it with the ‘test_string’ variable converted to a string using the ‘str()’ function.
- Use the ‘json.loads()’ function to convert the dictionary string to a dictionary object and assign it to the variable ‘res’.
- 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)) |
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 :
- The program imports the ast module.
- The program initializes a string variable test_string with a string representation of a dictionary: {“Nikhil” : 1, “Akshat” : 2, “Akash” : 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)).
- 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).
- 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)) |
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} |
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)) |
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.