How to add an element to a list? How to add an element to a list? json json

How to add an element to a list?


I would do this:

data["list"].append({'b':'2'})

so simply you are adding an object to the list that is present in "data"


Elements are added to list using append():

>>> data = {'list': [{'a':'1'}]}>>> data['list'].append({'b':'2'})>>> data{'list': [{'a': '1'}, {'b': '2'}]}

If you want to add element to a specific place in a list (i.e. to the beginning), use insert() instead:

>>> data['list'].insert(0, {'b':'2'})>>> data{'list': [{'b': '2'}, {'a': '1'}]}

After doing that, you can assemble JSON again from dictionary you modified:

>>> json.dumps(data)'{"list": [{"b": "2"}, {"a": "1"}]}'


import jsonmyDict = {'dict': [{'a': 'none', 'b': 'none', 'c': 'none'}]}test = json.dumps(myDict)print(test)

{"dict": [{"a": "none", "b": "none", "c": "none"}]}

myDict['dict'].append(({'a': 'aaaa', 'b': 'aaaa', 'c': 'aaaa'}))test = json.dumps(myDict)print(test)

{"dict": [{"a": "none", "b": "none", "c": "none"}, {"a": "aaaa", "b": "aaaa", "c": "aaaa"}]}