Reputation: 51
In my Python program, I have a string of format:
'name': 'Salman','age': '25', 'access': 'R', 'id': '00125'
I want to convert it to type dict so that I can query like dict["name"]
to get "Salman"
printed.
Upvotes: 2
Views: 4848
Reputation: 12157
I think this is a neat solution using comprehensions
s = "'name': 'Salman','age': '25', 'access': 'R', 'id': '00125'"
d = dict([i.strip().replace("'", "") for i in kv.split(':')] for kv in s.split(","))
# d == {'access': 'R', 'age': '25', 'id': '00125', 'name': 'Salman'}
Upvotes: 2
Reputation: 85
first split the string by ":" and "," and store it in a list. then iterate from 0 to len(list)-2: mydict[list[i]] = list[i+1]
Upvotes: 0
Reputation: 164623
Use ast.literal_eval
:
import ast
mystr = "'name': 'Salman','age': '25', 'access': 'R', 'id': '00125'"
d = ast.literal_eval('{'+mystr+'}')
# {'access': 'R', 'age': '25', 'id': '00125', 'name': 'Salman'}
d['access'] # 'R'
Upvotes: 9