4
\$\begingroup\$

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
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Can you show more of your code? Currently this seems somewhat hypothetical. \$\endgroup\$
    – Reinderien
    Nov 6 '20 at 14:38
6
\$\begingroup\$

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}]
\$\endgroup\$
1
  • \$\begingroup\$ 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 \$\endgroup\$ Nov 9 '20 at 16:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.