Search code examples
pythonzip

using zip with two dictionaries of different length


A={1:[1],2:[2],3:[3]}

B= {1:[5]}

summ = [a[0]+b[0] for (a,b) in zip(A.values(),B.values())]

print(summ)

summ = [6]

I have the above situation where I would like to sum the values corresponding to the same KEYS while keeping the non corresponding values at the same time, so that the solution in this case would be:

summ = [6, 2, 3]

How can I do it? It is not mandatory to zip the dictionary, but that's what I tried so far.


Solution

  • A list comprehension should do the trick:

    summ = [v[0] + B[k][0] if k in B else v[0] for k, v in A.items()]