0
dic1 = {
    'a':2,
    'b':3
}

dic2 = {
    'a':2,
    'b':3,
    'c':5
}
...

My particular question is more of a syntax in python question for my own satisfaction. Suppose you have a bunch of dictionaries and you want to add up all attributes a,b, and c which may not exist... My current code is kind of bulky and I'm not a fan of a bunch of if elif statements...

if 'a' in dicX:
   total+=dicX['a']
if 'b' in dicX:
   total+=dicX['b']
if 'c' in dicX:
   total+=dicX['c']

Can anyone recommend a better single line way of doing this? Or just a cleaner way to do this?

martineau
  • 112,593
  • 23
  • 157
  • 280

1 Answers1

0
{k : (dic1[k] if k in dic1 else 0) + (dic2[k] if k in dic2 else 0) 
 for k in dic1.keys() | dic2.keys()}
#{'b': 6, 'c': 5, 'a': 4}
DYZ
  • 51,549
  • 10
  • 60
  • 87