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

MickaëlG picture MickaëlG · Dec 28, 2012 · Viewed 53.6k times · Source

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.

Answer

vk1011 picture vk1011 · Jan 13, 2016

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'}]