Created
September 30, 2022 11:57
-
-
Save jansenicus/cc3ee3b86634e771a3326a1fcededdbf to your computer and use it in GitHub Desktop.
summing up keys over two dictionaries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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