Open In App

Python program to create a dictionary from a string

Improve
Improve
Like Article
Like
Save
Share
Report

Dictionary in python is a very useful data structure and at many times we see problems regarding converting a string to a dictionary. So, let us discuss how we can tackle this problem. Method # 1: Using eval() If we get a string input which completely resembles a dictionary object(if the string looks like dictionary as in python) then we can easily convert it to dictionary using eval() in Python. 

Python3




# Python3 code to convert
# a string to a dictionary
 
# Initializing String
string = "{'A':13, 'B':14, 'C':15}"
 
# eval() convert string to dictionary
Dict = eval(string)
print(Dict)
print(Dict['A'])
print(Dict['C'])


Output:

{'C': 15, 'B': 14, 'A': 13}
13
15

Method # 2: Using generator expressions in python If we get a string input does not completely resemble a dictionary object then we can use generator expressions to convert it to a dictionary. 

Python3




# Python3 code to convert
# a string to a dictionary
 
# Initializing String
string = "A - 13, B - 14, C - 15"
 
# Converting string to dictionary
Dict = dict((x.strip(), y.strip())
             for x, y in (element.split('-')
             for element in string.split(', ')))
 
print(Dict)
print(Dict['A'])
print(Dict['C'])


Output:

{'C': '15', 'A': '13', 'B': '14'}
13
15

The code given above does not convert integers to an int type,  if integers keys are there then just line 8 would work 

Python3




string = "11 - 13, 12 - 14, 13 - 15"
 
Dict = dict((x.strip(), int(y.strip()))
             for x, y in (element.split('-')
             for element in string.split(', ')))
 
print(Dict)


Output:

{'13': 15, '12': 14, '11': 13}

One additional approach that could be used to create a dictionary from a string is to use the json module. The json module allows you to parse a JSON string and convert it into a dictionary.

Here’s an example of how you could use the json module to create a dictionary from a string:

Python3




import json
 
# Initializing string
string = '{"key1": "value1", "key2": "value2"}'
 
# Parse the string into a dictionary using json.loads
dict = json.loads(string)
 
print(dict# {'key1': 'value1', 'key2': 'value2'}


Output

{'key1': 'value1', 'key2': 'value2'}

The json module is a part of the Python standard library, so you don’t need to install any additional modules to use it.

Time complexity for this approach is O(N), where N is the length of the string, as the json.loads function needs to parse the entire string to create the dictionary. The space complexity is also O(N), as the resulting dictionary will be the same size as the original string.



Last Updated : 30 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads