Python | Converting string content to dictionary



Method # 1: Using split () + understanding vocabulary
A combination of the above methods can be used to accomplish this particular task. These are 2 processes. In the first step, the string is converted to a list using split, and then converted back to a dictionary using dictionary comprehension.

# Python3 demo code
# Converting string content to dictionary
# Using dictionary comprehension + split ()

 
# initialization string

test_str = "Gfg = 1, Good = 2, CS = 3, Portal = 4"

 
# print original line

print ( " The original string is: " + test_str)

  
# Using dictionary comprehension + split ()
# Convert string content to dictionary

res = {key: int (val) for key, val in (item.split ( `=` )

for item in test_str.split ( `, ` ))}

 
# print result

print ( "The newly created dictionary:" + str (res))

Output:

 The original string is: Gfg = 1, Good = 2, CS = 3, Portal = 4 The newly created dictionary: {`CS`: 3, `Gfg`: 1, `Portal`: 4, `Good`: 2} 

Method # 2: Using eval ()
This particular problem can be solved with the built-in eval function which internally evaluates the string and converts the string to a dictionary depending on the condition.

# Python3 code to demonstrate how it works
# Convert string content to dictionary
# Using eval ()

 
# initialization string

test_str = "Gfg = 1, Good = 2, CS = 3, Portal = 4 "

  
# print original line

print ( "The original string is:" + test_str)

 
# Using eval ()
# Convert string content to dictionary

res = eval ( `dict (% s)` % test_str)

 
# print result

print ( " The newly created dictionary: " + str (res))