Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an element in each dictionary of a list (list comprehension)

I have a list of dictionaries, and want to add a key for each element of this list. I tried:

result = [ item.update({"elem":"value"}) for item in mylist ] 

but the update method returns None, so my result list is full of None.

result = [ item["elem"]="value" for item in mylist ] 

returns a syntax error.

like image 586
MickaëlG Avatar asked Dec 28 '12 14:12

MickaëlG


People also ask

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

Method 1: Using += sign on a key with an empty value In this method, we will use the += operator to append a list into the dictionary, for this we will take a dictionary and then add elements as a list into the dictionary.

Can I use list comprehension with dictionary?

Method 1: Using dict() methodUsing dict() method we can convert list comprehension to the dictionary. Here we will pass the list_comprehension like a list of tuple values such that the first value act as a key in the dictionary and the second value act as the value in the dictionary.

Can you append in list comprehension Python?

In the simplest of words, list comprehension is the process of creating a new list from an existing list. Or, you can say that it is Python's unique way of appending a for loop to a list. But, it is already pretty simple to declare a list and append anything you like to it.

How do you use list comprehension in Python dictionary?

List comprehensions are constructed from brackets containing an expression, which is followed by a for clause, that is [item-expression for item in iterator] or [x for x in iterator], and can then be followed by further for or if clauses: [item-expression for item in iterator if conditional].


2 Answers

If you want to use list comprehension, there's a great answer here: https://stackoverflow.com/a/3197365/4403872

In your case, it would be like this:

result = [dict(item, **{'elem':'value'}) for item in myList] 

Eg.:

myList = [{'a': 'A'}, {'b': 'B'}, {'c': 'C', 'cc': 'CC'}] 

Then use either

result = [dict(item, **{'elem':'value'}) for item in myList] 

or

result = [dict(item, elem='value') for item in myList] 

Finally,

>>> result [{'a': 'A', 'elem': 'value'},  {'b': 'B', 'elem': 'value'},  {'c': 'C', 'cc': 'CC', 'elem': 'value'}] 
like image 195
vk1011 Avatar answered Sep 28 '22 04:09

vk1011


You don't need to worry about constructing a new list of dictionaries, since the references to your updated dictionaries are the same as the references to your old dictionaries:

 for item in mylist:     item.update( {"elem":"value"}) 
like image 37
Jeffrey Theobald Avatar answered Sep 28 '22 02:09

Jeffrey Theobald