Islarf Islarf - 4 months ago 12
JSON Question

Python: add to a dictionary in a list

I have the following dictionary (It is for creating json),

temp = {'logs':[]}


I want to append dictionaries, but i only got 1 key:val at a time.

what I tried:

temp['logs'].append({key:val})


This does as expected and appends the dict to the array.
But now I want to add a key/val pair to this dictionary, how can I do this?
I've tried using append/extend but that just adds a new dictionary to the list.

Answer

But now I want to add a key/val pair to this dictionary

You can index the list and update that dictionary:

temp['logs'][0].update({'new_key': 'new_value'})
Comments