-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?

ppap
  • 251
  • 2
  • 15
  • use the json module – SuperStew Nov 21 '19 at 15:59
  • can you show me an example ? using this example above? – ppap Nov 21 '19 at 16:00
  • you can check here https://stackoverflow.com/questions/988228/convert-a-string-representation-of-a-dictionary-to-a-dictionary – Yukun Li Nov 21 '19 at 16:03
  • 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) – Jacob Nov 21 '19 at 16:04
  • i've seen the post yukun, but i'm running into this error raise ValueError('malformed node or string: ' + repr(node)) – ppap Nov 21 '19 at 16:06

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
  • 26,853
  • 21
  • 75
  • 114