-3

Let's say that I have a list of dictionaries that looks something like this in a string format

"[{key1:{key11:val11,key12:val12}},{key2:{key21:val21, key22:val22}}]"

How can i change this string(in the dictionary format) to an actual dictionary? while keeping the format?

Ryguy444222
  • 191
  • 1
  • 9

1 Answers1

1

This isn’t json data nor is it a dict it’s 2 separate dicts in a set which isn’t even correct. Although you can get both dicts as a tuple using ast.literal_eval if you format it correctly which can be done using re

data = "{{key1:{key11:val11,key12:val12}},{key2:{key21:val21, key22:val22}}}"
dicts = ast.literal_eval(re.sub(r'(\w+)', r'"\1"', data [1:-1]))

Result:

({'key1': {'key11': 'val11', 'key12': 'val12'}}, {'key2': {'key21': 'val21', 'key22': 'val22'}})
Jab
  • 25,138
  • 21
  • 72
  • 111