简体   繁体   English

从复杂的字符串中提取嵌套的Python字典

[英]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? 如何将其转换为Python字典? 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"' 输入: '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 } } } 预期结果: { 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 } } }

As TS mentioned, there are a string with a nested dictionary (first time I interpret it as an implicit reference to validity). 正如TS所提到的,有一个带有嵌套字典的字符串(我第一次将其解释为对有效性的隐式引用)。 If the string content is valid JSON you can use json built-in package includes all you need to parse it: 如果字符串内容是有效的 JSON,则可以使用json内置程序包包括解析所需的全部内容:

import json
data = json.loads(your_string)

Read more in JSON package docs . JSON包docs中阅读更多内容。

If not, you can write regular expression or use pyparsing package to process this string. 如果不是,则可以编写正则表达式或使用pyparsing包来处理此字符串。

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. 通过对输入进行一些编辑,可以由yaml加载它,并且数据对象是您所要求的一组嵌套字典。 How was the input string created ?. 输入字符串是如何创建的? The specific edits are : 具体编辑为:

  • change "data dict" id:" to "data dict"\\nid:", 将“ data dict” id:“更改为” data dict“ \\ nid:”,
  • change "\\n group_id" to "\\ngroup_id" 将“ \\ n group_id”更改为“ \\ ngroup_id”
  • change all { to : , 将所有{更改为:,
  • remove all } . 移除所有 } 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM