Skip to content

Instantly share code, notes, and snippets.

@jansenicus
Created September 30, 2022 11:57
Show Gist options
  • Save jansenicus/cc3ee3b86634e771a3326a1fcededdbf to your computer and use it in GitHub Desktop.
Save jansenicus/cc3ee3b86634e771a3326a1fcededdbf to your computer and use it in GitHub Desktop.
summing up keys over two dictionaries
d1 = {'key1': 50, 'key2': 100, 'key3':200}
d2 = {'key1': 200, 'key2': 100, 'key4':300}
# the concise way
from collections import Counter
new_dict = Counter(d1) + Counter(d2)
print(new_dict)
# the long way:
new_dict = {}
for j,u in d2.items():
for k,v in d1.items():
if j == k:
new_dict[k] = u + v
if k not in new_dict:
new_dict[k] = v
if j not in new_dict:
new_dict[j] = u
print(new_dict)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment