Python Forum

Full Version: Iterate through a list of dictionary and append a new value.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm trying to iterate through the following dictionary and append in the list .

dic={'Dining': [{'Switchboard': [{'Fan': ['01:45.9166666666']},
                             {'Covelight': ['01:116.5']},
                             {'Light': ['01:182.4']}]}],
 'Kids': [{'Switchboard': [{'Light': ['01:206.8']},
                           {'Fan': ['01:2.58333333333']}]}],
 'Kitchen': [{'MultiSensor': [{'Red': ['01:0.95125']}]},
             {'Switchboard': [{'Light2': ['01:125.2']},
                              {'Light': ['01:176.533333333']},
                              {'Fan': ['01:5.0']}]}],
 'Living': [{'Switchboard': [{'Light': ['01:7.13333333333']},
                             {'Covelight': ['01:17.6']},
                             {'Fan': ['01:6.91666666667']}]},
            {'MultiSensor': [{'Red': ['01:0.508333333333']},
                             {'Green': ['01:4.23333333333']}]}]}
for example if I want to append '02:3.9' in {'Green': ['01:4.23333333333']}
I would say that structure of data is rather complicated.

There are several layers of lists and following code relies on order (will break when order is changed or elements are added to lists; accessing last element in lists):

>>> dic['Living'][-1]['MultiSensor'][-1]['Green'].append('02:3.9')
By changing the code a little bit one can rely only on order and allow appending (utilizing indexes from start; accessing second element in lists)

>>> dic['Living'][1]['MultiSensor'][1]['Green'].append('02:3.9')
List of dictionaries is most useful when dictionaries are of similar structure.

With slightly adjusting datastructure (eliminating lists of dictionaries) it can be made more robust against possible additions, changes:

dic={'Dining': {'Switchboard': {'Fan': ['01:45.9166666666'], 'Covelight': ['01:116.5'], 'Light': ['01:182.4']}},
     
     'Kids': {'Switchboard':  {'Light': ['01:206.8'], 'Fan': ['01:2.58333333333']}},
     'Kitchen': {'MultiSensor': {'Red': ['01:0.95125']},
                 'Switchboard': {'Light2': ['01:125.2'], 'Light': ['01:176.533333333'], 'Fan': ['01:5.0']}},
     'Living': {'Switchboard': {'Light': ['01:7.13333333333'], 'Covelight': ['01:17.6'], 'Fan': ['01:6.91666666667']},
                'MultiSensor': {'Red': ['01:0.508333333333'], 'Green': ['01:4.23333333333']}}}



>>> dic['Living']['MultiSensor']['Green']   # you can append to that
['01:4.23333333333']
>>> dic['Kitchen']['Switchboard']['Fan']
['01:5.0']
>>> dic['Kitchen']['MultiSensor']['Green'] = ['01:5.123'] # add new key-value pair under 'MultiSensor'
>>> dic['Kitchen']['MultiSensor']
{'Red': ['01:0.95125'], 'Green': ['01:5.123']}