Salman
Salman

Reputation: 51

Create dict from string in Python

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

Answers (3)

FHTMitchell
FHTMitchell

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

Syed Muzamil
Syed Muzamil

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

jpp
jpp

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

Related Questions