# Increment value in a list of dictionaries

I have a list of dictionary let's say : l=[{'a':1,'b':2},{'a':5,'b':6},{'a':3,'b':2}] and I want to have another list l2 and add 4 to the 'a' in the all dictionaries
l2=[{'a':5,'b':2},{'a':9,'b':6},{'a':7,'b':2}] (the first list l shouldn't change) so I am doing it this way but i feel there is better, it is a bit hard coded I think :

 l=[{'a':1,'b':2},{'a':5,'b':6},{'a':3,'b':2}]
l2=[d.copy() for d in l]
for v in l2:
v['a']=v['a']+4

• Can you show more of your code? Currently this seems somewhat hypothetical. Nov 6 '20 at 14:38

Should have spaces around =, and += would shorten it a bit. And I'd be consistent with the variable name (not switch from d to v) and use better names for the lists (l looks too much like 1 and is just too short for something presumably living longer (unlike d, which I find ok in such small contexts)):

lst2 = [d.copy() for d in lst]
for d in lst2:
d['a'] += 4


I'd say that's alright then. But here are two alternatives:

>>> [d | {'a': d['a'] + 4} for d in lst]
[{'a': 5, 'b': 2}, {'a': 9, 'b': 6}, {'a': 7, 'b': 2}]

>>> [{**d, 'a': d['a'] + 4} for d in lst]
[{'a': 5, 'b': 2}, {'a': 9, 'b': 6}, {'a': 7, 'b': 2}]

• thank you , this is what I was looking for ,i was feeling it can be done in one line of code, and yes for the variables I know it was just a quick example of what I wanted to do in my real code I am using more significant variable names Nov 9 '20 at 16:27