Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,900 questions

51,831 answers

573 users

How to merge two dictionaries and sum the values in Python

4 Answers

0 votes
dict1 = {'a': 4, 'b': 3, 'c': 7, 'd': 9, 'e': 100}
dict2 = {'a': 1, 'b': 5, 'c': 2, 'f': 12, 'g': 50}

result = {key: dict1.get(key, 0) + dict2.get(key, 0) for key in dict1}

print(result)





'''
run:

{'a': 5, 'b': 8, 'c': 9, 'd': 9, 'e': 100}

'''

 



answered Jul 23, 2022 by avibootz
0 votes
dict1 = {'a': 4, 'b': 3, 'c': 7, 'd': 9, 'e': 100}
dict2 = {'a': 1, 'b': 5, 'c': 2, 'f': 12, 'g': 50}

result = {key: dict1.get(key, 0) + dict2.get(key, 0) for key in set(dict1) & set(dict2)}

print(result)





'''
run:

{'c': 9, 'b': 8, 'a': 5}

'''

 



answered Jul 23, 2022 by avibootz
0 votes
dict1 = {'a': 4, 'b': 3, 'c': 7, 'd': 9, 'e': 100}
dict2 = {'a': 1, 'b': 5, 'c': 2, 'f': 12, 'g': 50}

result = {key: dict1.get(key, 0) + dict2.get(key, 0) for key in dict2}

print(result)





'''
run:

{'a': 5, 'b': 8, 'c': 9, 'f': 12, 'g': 50}

'''

 



answered Jul 23, 2022 by avibootz
0 votes
dict1 = {'a': 4, 'b': 3, 'c': 7, 'd': 9, 'e': 100}
dict2 = {'a': 1, 'b': 5, 'c': 2, 'f': 12, 'g': 50}

result = {key: dict1.get(key, 0) + dict2.get(key, 0) for key in set(dict1) | set(dict2)}

print(result)





'''
run:

{'g': 50, 'f': 12, 'c': 9, 'd': 9, 'b': 8, 'e': 100, 'a': 5}

'''

 



answered Jul 23, 2022 by avibootz

Related questions

...