PixelatedPixie
PixelatedPixie

Reputation: 121

Extract nested Python dictionary from complex string

I have a complex string with a nested dictionary in it. This dictionary further has a list of three similar dictionaries inside it. How do I convert this into a Python dictionary? Please help.

Input: 'name: "data dict" id: 2\nv6: false\nstats {\n hosts {\n cnt1: 256\n cnt2: 0\n }\n groups {\n cnt1: 1\n cnt2: 0\n }\n main_groups {\n cnt1: 1\n cnt2: 0\n }\n main_hosts {\n cnt1: 256\n cnt2: 0\n }\n}\n group_id: "None"'

Expected result: { name: "data dict", id: 2, v6: false, stats: { hosts: { cnt: 1, cnt: 2 } groups: { cnt: 1, cnt: 2 } main: { cnt: 1, cnt: 2 } main_hosts: { cnt: 1, cnt: 2 } } }

Upvotes: 0

Views: 2579

Answers (2)

Bill Oldroyd
Bill Oldroyd

Reputation: 379

With some editing of your input, it can be loaded by yaml and the data object is as you have requested it, a set of nested dictionaries. How was the input string created ?. The specific edits are :

  • change "data dict" id:" to "data dict"\nid:",
  • change "\n group_id" to "\ngroup_id"
  • change all { to : ,
  • remove all } .

Upvotes: 0

Oleh Rybalchenko
Oleh Rybalchenko

Reputation: 8039

As TS mentioned, there are a string with a nested dictionary (first time I interpret it as an implicit reference to validity). If the string content is valid JSON you can use json built-in package includes all you need to parse it:

import json
data = json.loads(your_string)

Read more in JSON package docs.

If not, you can write regular expression or use pyparsing package to process this string.

Upvotes: 1

Related Questions