2

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.

3

3 Answers 3

9

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'
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.