python 如何从另一个字典动态填充嵌套字典

m4pnthwp  于 2022-12-25  发布在  Python
关注(0)|答案(2)|浏览(184)

我有一个函数,应该转换成正确的输入字典的格式。键的每个输入字典包含一个或多个->,以表明嵌套结构。

dict1 = {
    'p1->a->b': 1,
    'p1->a->c': 2,
    'p1->d': 4,
    'p2->a': 3
}
dict1_expected = {
    'p1': {
        'a': {
            'b': 1,
            'c': 2
        },
        'd': 4
    },
    'p2': {
        'a': 3
    }
}

def foo(input_dict):
    # Process input_dict
    return input dict

assert dict1_expected == foo(dict1)

现在,我只能通过下面的方式在一个层次上实现这一点:

dict1_expected = {}
for param in dict1:
    if param.split("->")[0] not in dict1_expected:
        dict1_expected.update({
            param.split("->")[0]: {
                param.split("->")[1]: dict1[param]
            }
        })
    else:
        dict1_expected[param.split("->")[0]].update({
            param.split("->")[1]: dict1[param]
        })
zfciruhq

zfciruhq1#

使用嵌套循环更容易,外循环迭代dict1的键值对,内循环迭代按->键拆分。

    • 代码:**
dict1 = {
    'p1->a->b': 1,
    'p1->a->c': 2,
    'p1->d': 4,
    'p2->a': 3,
    'c': 0
}
dict1_expected = {}

for key, value in dict1.items():
    current_dict = dict1_expected
    *parts, last = key.split('->')
    for part in parts:
        if part not in current_dict:
            current_dict[part] = {}
        current_dict = current_dict[part]
    current_dict[last] = value
    • 结果**:
{
    'p1': {
        'a': {
            'b': 1, 
            'c': 2
        }, 
        'd': 4
    }, 
    'p2': {
        'a': 3
    }, 
    'c': 0
}
z9smfwbn

z9smfwbn2#

我想到了这个:

def foo(input_dict):
    # Process input_dict
    res = {}
    for path, value in input_dict.items():
        curr = res
        components = path.split('->')
        for c in components[:-1]:
            curr = curr.setdefault(c, {})

        curr[components[-1]] = value

    return res

相关问题