Python | Converting String content to dictionary
Last Updated :
27 Apr, 2023
Sometimes, we are fed with string and we may have to convert it’s content to dictionary. The string may have a specified format that could be key-value convertible. This type of problem is quite common in Machine Learning domain. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using split() + dictionary comprehension The combination of above method can be used to perform this particular task. This is 2 process method. In 1st step, the string is converted to list using split and then converted back to dictionary using dictionary comprehension.
Python3
test_str = "Gfg = 1, Good = 2, CS = 3, Portal = 4 "
print ( "The original string is : " + test_str)
res = {key: int (val) for key, val in (item.split( '=' )
for item in test_str.split( ', ' ))}
print ( "The newly created dictionary : " + str (res))
|
Output
The original string is : Gfg = 1, Good = 2, CS = 3, Portal = 4
The newly created dictionary : {'Gfg ': 1, 'Good ': 2, 'CS ': 3, 'Portal ': 4}
Time complexity: O(n*n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), to store the keys and values in dictionary.
Method #2 : Using eval() This particular problem can be solved using the inbuilt function eval which internally evaluates the string and converts the string to dictionary depending upon the condition.
Python3
test_str = "Gfg = 1, Good = 2, CS = 3, Portal = 4"
print ( "The original string is : " + test_str)
res = eval ( 'dict(% s)' % test_str)
print ( "The newly created dictionary : " + str (res))
|
Output
The original string is : Gfg = 1, Good = 2, CS = 3, Portal = 4
The newly created dictionary : {'Gfg': 1, 'Good': 2, 'CS': 3, 'Portal': 4}
Method #3 : Using split(),index() and slicing
Python3
test_str = "Gfg = 1, Good = 2, CS = 3, Portal = 4"
print ( "The original string is : " + test_str)
res = dict ()
x = test_str.split( "," )
for i in x:
a = i[:i.index( "=" )]
b = i[i.index( "=" ) + 1 :]
res[a] = b
print ( "The newly created dictionary : " + str (res))
|
Output
The original string is : Gfg = 1, Good = 2, CS = 3, Portal = 4
The newly created dictionary : {'Gfg ': ' 1', ' Good ': ' 2', ' CS ': ' 3', ' Portal ': ' 4'}
Share your thoughts in the comments
Please Login to comment...