在python中创建具有重复键的嵌套词典

2024-06-01 19:05:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下字典:

d = {    
    'results.household.land_tenure_access_restitution.has_land_allocated_relation': ['false', 'true'],
        "results.household.land_tenure_access_restitution.is_status_of_claim_required": ["false", "true"]
     }

我需要创建以下内容:

^{pr2}$

我写了以下代码:

f = {}
g = {}
for key, value in d.iteritems():
    print f
    for n, k in enumerate(reversed(key.split('.'))):
        if n == 0:
            f = {k: d[key]}
        else:
            f = {k: f}

g.update(f)

但是,字典会被最新的键值覆盖,因为上层的键不是唯一的。我得到这个输出:

{
'results': {
    'household': {'land_tenure_access_restitution': {
        'has_land_allocated_relation': ['false', 'true']
}}}}

如何达到上述结果?在


Tags: keyinfalsetruefor字典accessresults
2条回答

您的更新过程太晚了:请注意,只有当您遍历了整个字符串并返回到dict的顶层时,才能进行更新。只要根匹配,就替换整个树。在

您需要从树的根results开始向下遍历,直到您检测到需要更新,即现有结构与当前字符串之间的差异。然后解析剩余的字符串并构建要添加的子树,在到达字符串末尾时更新。在

这对你做编码有足够的提示吗?在

您可以递归地合并字典:

from functools import reduce
import collections

d = {
    'results.household.land_tenure_access_restitution.has_land_allocated_relation': ['false', 'true'],
    "results.household.land_tenure_access_restitution.is_status_of_claim_required": ["false", "true"]
}


def dict_merge(dct, merge_dct):
    for key, value in merge_dct.items():
        if key in dct and isinstance(dct[key], dict) and isinstance(merge_dct[key], collections.Mapping):
            dict_merge(dct[key], merge_dct[key])
        else:
            dct[key] = merge_dct[key]

result = {}
for k, v in d.items():
    elements = [v] + list(reversed(k.split('.')))
    nested = reduce(lambda x, y: {y: x}, elements)
    dict_merge(result, nested)

print(result)

输出

^{pr2}$

函数dict_merge递归地合并两个字典,行:

elements = [v] + list(reversed(k.split('.')))
nested = reduce(lambda x, y: {y: x}, elements)

为原始字典的每个键创建一个嵌套字典。在

相关问题 更多 >