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