SwissFr
0
Q:

python string to dict

# 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}' 

# using ast.literal_eval() 
# convert dictionary string to dictionary 
res = ast.literal_eval(test_string) 
  
0
# 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)) 
5
>>> D1={'1':1, '2':2, '3':3}
>>> s=str(D1)
>>> import ast
>>> D2=ast.literal_eval(s)
>>> D2
{'1': 1, '2': 2, '3': 3}

3
# Python3 code to convert a 
# string to a dictionary if 
# string is not in dictionary form

# 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']) 
3
>>> import ast
>>> ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}")
{'muffin': 'lolz', 'foo': 'kitty'}
0

New to Communities?

Join the community