d1={a:1,b:2,c:3}
d2={a:4,b:5,c:6}
d3={a:7,b:8,c:9}
how do I add all the keys of dictionary d1 d2 and d3, to get the output:
d4={a:12,b:15,c:18}
CodePudding user response:
You can use a dictionary comprehension:
d1={'a':1,'b':2,'c':3}
d2={'a':4,'b':5,'c':6}
d3={'a':7,'b':8,'c':9}
d4 = {k: d1[k] d2[k] d3[k] for k in d1}
print(d4)
Output:
{'a': 12, 'b': 15, 'c': 18}
CodePudding user response:
Eli already has suggested a fine solution, but in case there is anyone looking for something for general, you may also try:
import operator
def combine_dicts(a,b, op=operator.add):
return {**dict(a.items() | b.items()), **dict([(k, op(a[k],b[k])) for k in set(b) & set(a)])}
d4 = combine_dicts(combine_dicts(d1, d2),d3)
print(d4)
Output:
{'c': 18, 'b': 15, 'a': 12}
This is adapted for newer versions of Python (like >=3.5) from the answer kabooya suggested in his comment.
In case you have more dictionaries, you can put them into a list and then iterate with this method.
CodePudding user response:
Will it always be 3 X 3 with a,b,c or will the number and length of dictionary's change ? Will they always be the same length?
