0

Okay, so you can change an element in a list with simple number values this way:

>>> a=[1,2,3,4,5,1,2,3,4,5,1]
>>> for n,i in enumerate(a):
...   if i==1:
...      a[n]=10
...
>>> a
[10, 2, 3, 4, 5, 10, 2, 3, 4, 5, 10]

and with list comprehension:

>>> a=[1,2,3,1,3,2,1,1]
>>> a = [4 if x==1 else x for x in a]
>>> a
[4, 2, 3, 4, 3, 2, 4, 4]

But if I have a list of dictionaries, can I change not only an element but one of its property as well, using list comprehension? Is there some expression for that?

MattSom
  • 2,097
  • 5
  • 31
  • 53
  • 2
    Trying using both list and [dictionary comprehensions](https://stackoverflow.com/questions/14507591/python-dictionary-comprehension); add conditional expressions as you would a list comprehension. Note, in the first example, it's bad practice to change a list you are iterating over. Fix it like this: `enumerate(a[:])` (iterating over a copy of list `a`). In the second example, you aren't "changing" the list, but actually you are creating a new one and reassigning it to `a`. – pylang Apr 02 '17 at 23:03

1 Answers1

1

Is this what you were looking for:

a = [{1: [1,2,3], 2: [3,4,5]}]

a = [{k: [1,1,1]} if k == 2 else {k: v} for x in a for k, v in x.items()]
zipa
  • 27,316
  • 6
  • 40
  • 58