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.
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:
You can use map.
If you already have the list of lements you can do:
then you have the results
@vk1011's answer is good and can be extended with the spread operator concisely and new dictionary objects are an added benefit
To override any existing key's value with the new one you can put the spread operator before the new item
To override the new entry's value with an existing one, use the spread operator after the new item
Both methods will give a list of dictionary objects including the new item
Either do not use a list comprehension, or return a new dict based on the original dict plus the new key:
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:
Eg.:
Then use either
or
Finally,
You are using a list comprehension incorrectly, the call to
item.update
returns aNone
value and thus your newly created list will be full ofNone
values instead of your expecteddict
values.You need only to loop over the items in the list and update each accordingly, because the list holds references to the
dict
values.