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.
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.
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.
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.
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].
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'}]
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"})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With