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.

ayhan
  • 70,170
  • 20
  • 182
  • 203
Salman
  • 51
  • 1
  • 4
  • 1
    Write a regular expression or split it by comma and trim or try to have the string as json in first place. Show us what you've tried till now. – hspandher Feb 16 '18 at 14:12
  • 1
    Possible duplicate with : https://stackoverflow.com/questions/988228/convert-a-string-representation-of-a-dictionary-to-a-dictionary – Chuk Ultima Feb 16 '18 at 14:13
  • 1
    Possible duplicate of [Convert a String representation of a Dictionary to a dictionary?](https://stackoverflow.com/questions/988228/convert-a-string-representation-of-a-dictionary-to-a-dictionary) – Vaulstein Feb 16 '18 at 14:15

3 Answers3

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'
jpp
  • 159,742
  • 34
  • 281
  • 339
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'}
FHTMitchell
  • 11,793
  • 2
  • 35
  • 47
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]