使用字符串列表构建嵌套字典

时间:2018-03-20 16:31:49

标签: python nested

我需要根据配置文件构建一个嵌套的字典。

我有:

Chain1 {
    Chain1_value1
    Chain1_Chain2 {
    Chain1_Chain2_value1
        Chain1_Chain2_Chain3 {
            Chain1_Chain2_Chain3_value1
            Chain1_Chain2_Chain3_value2
            Chain1_Chain2_Chain3_value3
        }
        Chain1_Chain2_Chain4 {
            Chain1_Chain2_Chain4_value1
            Chain1_Chain2_Chain4_value2
            Chain1_Chain2_Chain4_value3
        }
    }
}

“XXX {”=>打开名为XXX的块

“XXX}”=>关闭名为XXX

的集团

如果没有“{”或“}”=>它是块的值。

我需要这个:

{'Chain1 {': {'Chain1_Chain2 {': {'Chain1_Chain2_Chain3 {': {'Chain1_Chain2_Chain3_value1': '',
                                                             'Chain1_Chain2_Chain3_value2': '',
                                                             'Chain1_Chain2_Chain3_value3': '',}}
                                  'Chain1_Chain2_Chain4 {': {'Chain1_Chain2_Chain4_value1': '',
                                                            'Chain1_Chain2_Chain4_value2': '',
                                                            'Chain1_Chain2_Chain4_value3': ''}},
                                  'Chain1_Chain2_value1': ''},
              'Chain1_value1': ''}}

但目前我有这个:

{'Chain1 {': {'Chain1_Chain2 {': {'Chain1_Chain2_Chain3 {': {'Chain1_Chain2_Chain3_value1': '',
                                                             'Chain1_Chain2_Chain3_value2': '',
                                                             'Chain1_Chain2_Chain3_value3': '',
                                                             'Chain1_Chain2_Chain4 {': {'Chain1_Chain2_Chain4_value1': '',
                                                                                        'Chain1_Chain2_Chain4_value2': '',
                                                                                        'Chain1_Chain2_Chain4_value3': ''}},
                                  'Chain1_Chain2_value1': ''},
              'Chain1_value1': ''}}

我的代码:

import re
import pprint

a = []
a.append("Chain1 {")
a.append("    Chain1_value1")
a.append("    Chain1_Chain2 {")
a.append("    Chain1_Chain2_value1")
a.append("        Chain1_Chain2_Chain3 {")
a.append("            Chain1_Chain2_Chain3_value1")
a.append("            Chain1_Chain2_Chain3_value2")
a.append("            Chain1_Chain2_Chain3_value3")
a.append("        }")
a.append("        Chain1_Chain2_Chain4 {")
a.append("            Chain1_Chain2_Chain4_value1")
a.append("            Chain1_Chain2_Chain4_value2")
a.append("            Chain1_Chain2_Chain4_value3")
a.append("        }")
a.append("    }")
a.append("}")

for l in a:
    print l
dict_test = {}
current_dict = dict_test
for line in a:
    line = line.strip()
    if re.search(r"{$", line):
        current_dict[line] = {}
        current_dict = current_dict[line]
    elif re.search(r'}$', line):
        pass
    else:
        current_dict[line] = ""
pprint.pprint(dict_test)

我想,这里错过了一些东西:elif re.search(r'} $',line) 但我不知道是什么。

你可以帮帮我吗? :)

2 个答案:

答案 0 :(得分:1)

您可以使用parse方法创建一个类:

import re
new_s = iter([re.sub('^\s+', '', i) for i in filter(None, 
s.split('\n'))])
from collections import defaultdict
class DictObject:
  def __init__(self, d):
    self.d = d
    self.current_dict = {}
    self.parse()
  def parse(self):
    while True:
      current = next(self.d, None)
      if not current:
        break
      if current.endswith('{'):
        second_piece = DictObject(self.d)
        self.current_dict[current] = second_piece.current_dict
        self.d = second_piece.d
      elif current == '}':
        break
      else:
        self.current_dict[current] = ''
        print(self.current_dict)


c = DictObject(new_s)
print(c.current_dict)

输出:

{'Chain1 {': {'Chain1_Chain2 {': {'Chain1_Chain2_Chain3 {': {'Chain1_Chain2_Chain3_value1': '',
                                                         'Chain1_Chain2_Chain3_value2': '',
                                                         'Chain1_Chain2_Chain3_value3': ''},
                              'Chain1_Chain2_Chain4 {': {'Chain1_Chain2_Chain4_value1': '',
                                                         'Chain1_Chain2_Chain4_value2': '',
                                                         'Chain1_Chain2_Chain4_value3': ''},
                              'Chain1_Chain2_value1': ''},
          'Chain1_value1': ''}}

答案 1 :(得分:0)

您没有跟踪字典的历史。我添加了previous_dict,并在'}'时将dict恢复到最后的值。存在。请在下面找到解决方案希望它有所帮助。

import re
import pprint

def get_data() : 
    a = []
    a.append("Chain1 {")
    a.append("    Chain1_value1")
    a.append("    Chain1_Chain2 {")
    a.append("    Chain1_Chain2_value1")
    a.append("        Chain1_Chain2_Chain3 {")
    a.append("            Chain1_Chain2_Chain3_value1")
    a.append("            Chain1_Chain2_Chain3_value2")
    a.append("            Chain1_Chain2_Chain3_value3")
    a.append("        }")
    a.append("        Chain1_Chain2_Chain4 {")
    a.append("            Chain1_Chain2_Chain4_value1")
    a.append("            Chain1_Chain2_Chain4_value2")
    a.append("            Chain1_Chain2_Chain4_value3")
    a.append("        }")
    a.append("    }")
    a.append("}")   
    return a


def get_dict(input_chain):
    dict_test = {}
    current_dict = dict_test
    previous_dict = dict_test #this was missing
    for line in input_chain:
        line = line.strip()
        if re.search(r"{$", line):
            previous_dict = current_dict
            current_dict[line] = {}
            current_dict = current_dict[line]
        elif re.search(r'}$', line):
            current_dict = previous_dict #revert to last dict at the end of the block
        else:
            current_dict[line] = ""

    return dict_test


def main():
    a = get_data()
    b = get_dict(a)
    pprint.pprint(b)


if __name__ == '__main__':
    main()

<强>输出

{'Chain1 {': {'Chain1_Chain2 {': {'Chain1_Chain2_Chain3 {': {'Chain1_Chain2_Chain3_value1': '',
                                                             'Chain1_Chain2_Chain3_value2': '',
                                                             'Chain1_Chain2_Chain3_value3': ''},
                                  'Chain1_Chain2_Chain4 {': {'Chain1_Chain2_Chain4_value1': '',
                                                             'Chain1_Chain2_Chain4_value2': '',
                                                             'Chain1_Chain2_Chain4_value3': ''},
                                  'Chain1_Chain2_value1': ''},
              'Chain1_value1': ''}}