-4

Create a list of dictionaries, and then add a key:value pair to each dictionary using assignment:

my_list_of_dicts = [{'a':1}, {'b':2}, {'c':3}]
x = [elem['c']=3 for elem in my_list_of_dicts]
  File "<stdin>", line 1
    x = [elem['c']=3 for elem in my_list_of_dicts]
                  ^
SyntaxError: invalid syntax

It works in a for loop, but not as a list comprehension. Why is that?

for elem in my_list_of_dicts:
     elem['c']=3
 
my_list_of_dicts
[{'a': 1, 'c': 3}, {'b': 2, 'c': 3}, {'c': 3}]
voortuck
  • 3
  • 2
  • Because you're supposed to write that as a loop. – superb rain Aug 16 '20 at 19:31
  • Does this answer your question? [How can I do assignments in a list comprehension?](https://stackoverflow.com/questions/10291997/how-can-i-do-assignments-in-a-list-comprehension) – efont Aug 16 '20 at 19:34
  • 1
    "It works in a for loop, but not as a list comprehension. Why is that?"—because `for` loops and list comprehensions are completely different things. A list comprehension isn't a loop. Use the right tool for the job. – Chris Aug 16 '20 at 19:39
  • Does this answer your question? [What does "list comprehension" mean? How does it work and how can I use it?](https://stackoverflow.com/questions/34835951/what-does-list-comprehension-mean-how-does-it-work-and-how-can-i-use-it) – Chris Aug 16 '20 at 19:52
  • The above link doesn't answer why an assignment doesn't work in this case. I'm not asking what a list comprehension is, I'm asking why assignment doesn't work for a dictionary in this case. – voortuck Aug 17 '20 at 20:30

2 Answers2

1

List comprehension doesn't support assignment in that way. Essentially what it does is create a new list by iterating through the old one. Look at the variable X. It's not being assigned anything because the variable assignment has no output.

Its generally a rule of thumb that every list comprehension can be written as a for-loop but not vice-versa.

0

You can not use assignement in a comprehension. Moreover, it is use usually a bad idea to use in-place modification in a comprehension.

You could do :

>>> ld = [{'a':1}, {'b':2}, {'c':3}]
>>> ld2 = [d.update({"c":3}) for d in ld]

But the content of ld2 will not be your modified dictionary. it will be [None, None, None] and the variable ld had been edited in-place.

For in-place modification, use a for-loop.

for my_dict in my_list_of_dict:
    my_dict.update({"c",3})