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

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

Leave a Comment