0

Code looks very lengthy, is there more elegant way to solve this, i am just a beginner.

# NOTE: Don't use any packages, i know it can be solved by importing counter from collections

    d1 = {'a': 100, 'b': 200, 'c':300}
    d2 = {'a': 300, 'b': 200, 'd':400}

    d={}
    for i,j in d1.items():
        for k,l in d2.items():
            if i==k:
                c={i:j+l}
                d.update(c)
    for i,j in d1.items():
        if i not in d:
            d.update({i:j})
    for m,n in d2.items():
        if m not in d:
            d.update({m:n})

Expected output:

output: {'a': 400, 'b': 400, 'c': 300, 'd': 400}
martineau
  • 119,623
  • 25
  • 170
  • 301
Loki
  • 33
  • 1
  • 9
  • Not a huge difference, but you could combine your first two `for i,j in d1.items():` loops. – Xorgon Jun 19 '19 at 23:00

1 Answers1

4

Do something like this:

d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}

all_keys = list(d1.keys())+list(d2.keys())
d ={}
for k in all_keys:
    d[k] = d1.get(k,0)+d2.get(k,0)

print(d)
arajshree
  • 626
  • 4
  • 13