Python:基于列表的树到基于dict的树

Python:基于列表的树到基于dict的树,python,tree,key-value,Python,Tree,Key Value,我正在处理一个解析器的输出,该解析器以嵌套列表的形式输出一棵树。以下是数据示例: [[['events'], [['worker_connections', '1024']]], [['http'], [['include', 'mime.types'], ['default_type', 'application/octet-stream'], ['sendfile', 'on'], ['keepalive_timeout', '65'], [['server']

我正在处理一个解析器的输出,该解析器以嵌套列表的形式输出一棵树。以下是数据示例:

[[['events'], [['worker_connections', '1024']]],
 [['http'],
  [['include', 'mime.types'],
   ['default_type', 'application/octet-stream'],
   ['sendfile', 'on'],
   ['keepalive_timeout', '65'],
   [['server'],
    [['listen', '8080'],
     ['server_name', 'localhost'],
     [['location', '/ '],
      [['root', 'html'], ['index', 'index.html index.htm']]],
     ['error_page', '500 502 503 504 /50x.html'],
     [['location', '= /50x.html '], [['root', 'html']]]]]]]]

将其转换为键值的每一种方法都会导致列表哈希性错误。有什么想法吗?

我觉得数据是明确的。逻辑上,它是一个字符串的dict,指向另一个此类dict,或者指向一个字符串。如果键指向dict,则表示为单元素列表,否则表示为字符串

当然,这是部分猜测,但如果我是对的,那么您可以这样转换:

def convert(a):
  result = {}
  for e in a:
    if isinstance(e[0], list):  # pointing at dict
      result[e[0][0]] = convert(e[1])
    else:
      result[e[0]] = e[1]
  return result
结果将是

{'events': {'worker_connections': '1024'},
 'http': {'default_type': 'application/octet-stream',
          'include': 'mime.types',
          'keepalive_timeout': '65',
          'sendfile': 'on',
          'server': {'error_page': '500 502 503 504 /50x.html',
                     'listen': '8080',
                     'location': {'root': 'html'},
                     'server_name': 'localhost'}}}
编辑:

我刚刚看到这会删除一些信息(当键是一个列表而不是像at
['location','/']
那样的一个元素列表时)。因此,我们可以使用元组作为键(它们是可散列的),最终结果如下:

def convert(a):
  result = {}
  for e in a:
    if isinstance(e[0], list):  # pointing at dict
      result[tuple(e[0])] = convert(e[1])
    else:
      result[e[0]] = e[1]
  return result
制作:

{('events',): {'worker_connections': '1024'},
 ('http',): {'default_type': 'application/octet-stream',
             'include': 'mime.types',
             'keepalive_timeout': '65',
             'sendfile': 'on',
             ('server',): {'error_page': '500 502 503 504 /50x.html',
                           'listen': '8080',
                           'server_name': 'localhost',
                           ('location', '/ '): {'index': 'index.html index.htm',
                                                'root': 'html'},
                           ('location', '= /50x.html '): {'root': 'html'}}}}

你能展示相同数据的基于dict的树吗,这样我们就可以看到它应该如何构造?我很确定我能理解,但可能有点含糊不清,因为我用
pprint
编辑了你的问题,使之可读。我现在不太确定你到底想要什么我觉得数据是明确的。逻辑上,它是一个字符串的dict,指向另一个此类dict,或者指向一个字符串。如果键指向dict,则表示为单元素列表,否则表示为字符串。我认为转换可以自动化。太棒了。非常感谢。事实证明,在尝试将它们用作键之前,我并没有从列表中提取单个项键。