0

I want to convert a string into dictionary. I've tried eval and literal_eval it doesn't work, since there are no quotes for keys.

str_to_convert = "{rpd.col_A : 'Type B', rpd_dev : 'Other, specify', rpd_form : 'Other'}"

Please note that rpd_dev: 'Other, specify', there is comma within the string which needs to be preserved. How can I achieve this in python?

Zakyl
  • 63
  • 5

3 Answers3

2

To load it as JSON for example, you would need double quote " around each key and value, the easiest seems to use a regex

import re

str_to_convert = "{rpd.col_A : 'Type B', rpd_dev : 'Other', rpd_form : 'Other'}"
result = re.findall(r"([\w.]+)\s*:\s*'([\w\s]+)'", str_to_convert)
print(dict(result))  # {'rpd.col_A': 'Type B', 'rpd_dev': 'Other', 'rpd_form': 'Other'}
azro
  • 53,056
  • 7
  • 34
  • 70
  • I have a case in which rpd_form : 'Other, specify' The above code fails for this scenario, since there is a comma within the string, how can I fix it? – Zakyl Oct 13 '21 at 07:36
  • Change to `([\w.]+)\s*:\s*'([\w,\s]+)'` or `([\w.]+)\s*:\s*'(.+?)'` – azro Oct 13 '21 at 17:30
0

I think you could use yaml for something like this, just need to remove the braces and the commas.

import yaml

str_to_convert = "{rpd.col_A : 'Type B', rpd_dev : 'Other', rpd_form : 'Other'}"
res = yaml.load(str_to_convert.replace(", ", "\n").strip("{}"), Loader=yaml.FullLoader)
print(res)

Output

{'rpd.col_A': 'Type B', 'rpd_dev': 'Other', 'rpd_form': 'Other'}

Note

yaml is a third-party module so you need to installing by running:

pip install pyyaml
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
0

You can use some AST-lib for decode it - as example ast.literal_eval as here or work with json - as here

Vasily
  • 173
  • 11