字典字典的扁平化引发了 AttributeError

Flattening of dictionary of dictionaries raises AttributeError

我有字典:

dict1 = {
    'conf1' : {'subconf11' : True, 'subconf12' : False}, 
    'conf2' : False, 
    'conf3' : {'subconf31' : True, 'subconf32' : False, 'subconf33' : False}, 
    'conf4' : 'On'
}

我想将其展平为元组列表,这样:

list1 = [
    ('conf1',('subconf11',True)),
    ('conf1',('subconf12',False)),
    ('conf2',False),
    ('conf3',('subconf31',True)),
    ('conf3',('subconf32',False)),
    ('conf3',('subconf33',False)),
    ('conf4','On')
]

我试过类似的方法:

primary_conf_list = list(dict1.keys())
list2 = [(i,list[dict1[i].items()]) for i in primary_conf_list]

但可以理解,对于那些值不是字典而是布尔值或字符串值的值,它会抛出错误。例如 dict1['conf2']dict1['conf4'].

这是确切的错误消息:

AttributeError: 'bool' object has no attribute 'items'

请帮我实现这个。

您应该检查该值是否为字典。如果是,则使用嵌套循环将元素添加到每个项目的结果中。

list2 = []
for key, val in dict1.items():
    if isinstance(val, dict):
        for subkey, subval in val.items():
            list2.append((key, (subkey, subval)))
    else:
        list2.append(key, val)