Home > Back-end >  Flattening of dictionary of dictionaries raises AttributeError
Flattening of dictionary of dictionaries raises AttributeError

Time:10-22

I have a dictionary:

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

I want to flatten it to a list of tuples, such that:

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

I tried something like:

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

But understandably it throws me error for those where the value is not a dictionary but either a bool or a string value. For example dict1['conf2'] and dict1['conf4'].

Here is the exact error message:

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

Please help me to achieve this.

CodePudding user response:

You should check if the value is a dictionary. If it is, use a nested loop to add elements to the result for each item.

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)
  • Related