Python如何地柜解析这种数据类型,data__key__hello = "world"
问题描述
比如有这么一个字典:
{ ’data__key_hello’: 'world', ’data__key_bar’: 'foo', ’data__a’: 'b', ’b’: ’c’,}
转换之后变成
{ ’data’: {’key’: { ’hello’: ’world’, ’bar’: ’foo’},’a’: ’b’, }, ’b’: ’c’}
就是以下划线进行一个分割
问题解答
回答1:# coding: utf-8def parse_dict(obj={}): result = {} for key in obj:value = obj[key]parse_key_value(key, value, result) return resultdef parse_key_value(key, value, result={}): if not key:return head = ’’ while 1:head, _, tail = key.partition(’_’) if head: breakkey = tail if head not in result:if tail: result[head] = {} else: result[head] = value return parse_key_value(tail, value, result[head])obj = { ’data__key_hello’: 'world', ’data__key_bar’: 'foo', ’data__a’: 'b', ’b’: ’c’,}print parse_dict(obj)回答2:
凑合着用吧
d = { ’data__key_hello’: 'world', ’data__key_bar’: 'foo', ’data__a’: 'b', ’b’: ’c’,}n = {}for k, v in d.items(): keys = k.replace(’__’, ’_’).split(’_’) child = n for i, key in enumerate(keys):child = child.setdefault(key, {} if i < len(keys) - 1 else v)print n