Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an element to a list?

Tags:

python

json

list

From this..

data = json.loads(urlopen('someurl').read())

...I will get:

{'list': [{'a':'1'}]}

I want to add {'b':'2'} into the list.

Any idea how to do it?

like image 506
doniyor Avatar asked May 20 '15 13:05

doniyor


People also ask

How do you add an element to a list in Java?

There are two methods to add elements to the list. add(E e ) : appends the element at the end of the list. Since List supports Generics , the type of elements that can be added is determined when the list is created. add(int index , E element ) : inserts the element at the given index .

Can we add element in list?

Elements can be added in the list using built-in functions like append(), insert(). append() adds the elements at the end of the list, while insert() adds the element at the specified position. extend() function and + operator is used to concatenate elements from one list/tuple into the other.

Can you add items to a list in Python?

Python provides a method called .append() that you can use to add items to the end of a given list.

Which function is used to add an element to a list?

append() and . extend() methods to add elements to a list. You can add elements to a list using the append method. The append() method adds a single element towards the end of a list.


2 Answers

I would do this:

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

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

like image 64
pinturic Avatar answered Nov 02 '22 00:11

pinturic


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"}]}'
like image 9
myaut Avatar answered Nov 02 '22 00:11

myaut