将一级字典转换为嵌套字典的结构

时间:2013-09-26 14:31:39

标签: python

鉴于字典的这种结构:

{
   'property1': 'value1',
   'property2.property3': 'value2',
   'property2.property7': 'value4',
   'property4.property5.property6': 'value3',

}

需要转换为此外观:

{
   'property1': 'value1',
   'property2': { 
                'property3': 'value2',
                'property7': 'value4'
              },
   'property4': { 
                'property5': { 
                             'property6': 'value3'
                           }
              }
}

只是简单的例子。我想看看最优化和美观的解决方案。显然它应该是将第一个字典作为输入并输出第二个字典的函数。

2 个答案:

答案 0 :(得分:1)

Quick'n'dirty解决方案。似乎工作,但如果有一个更简单的方法,我不会感到惊讶。

from collections import defaultdict

def default():
    return defaultdict(default)

def convert(src):
    dest = default()
    for key, val in src.iteritems():
        cursor = dest
        path = key.split('.')
        for path_elem in path[:-1]:
            cursor = cursor[path_elem]
        cursor[path[-1]] = val
    return dest

def to_regular_dict(val):
    # optional, if you do not want to carry defaultdicts around
    if isinstance(val, defaultdict):
        return {key:to_regular_dict(val) for key, val in val.iteritems()}
    else:
        return val

src = {
   'property1': 'value1',
   'property2.property3': 'value2',
   'property2.property7': 'value4',
   'property4.property5.property6': 'value3',
}

print convert(src)
print to_regular_dict(convert(src))

答案 1 :(得分:1)

正如我所说,非常简单。

def transform(inp):
    destination = {}

    for key, value in inp.items():
        keys = key.split(".")
        d = destination
        for key in keys[:-1]:
            if key not in d:
                d[key] = {}    
            d = d[key]

        d[keys[-1]] = value

    return destination

测试:

inp = {
   'property1': 'value1',
   'property2.property3': 'value2',
   'property2.property7': 'value4',
   'property4.property5.property6': 'value3',

}

output = transform(inp)

print output

{'property1': 'value1',
 'property2': {
    'property3': 'value2',
    'property7': 'value4'
}
,'property4': {
    'property5': {
        'property6': 'value3'
    }
}}