Hi Guys, welcome to my blog in this article you will learn about how to Write A Python Program To Combine Two Dictionary Adding Values For Common Keys
Title :
Write A Python Program To Combine Two Dictionary Adding Values For Common Keys
Description :
Hi in this article you will learn a python program on how to combine two dictionary data structures in to one by adding their values if they have common keys
Let's take two dictionaries: Variable storage 1 and storage 2, storage one contains four types of fruits.
Storage 2 contains three types of fruits, if you notice the below storage dictionary variables you find Orange as a common key present between two storages.
Storage one contains 20 pieces of oranges and storage contains 30 pieces of oranges so the resultant storage should be containing 50 oranges.
storage1 = {"apple": 10, "orange": 20, "banana":30, "strawberry":40 }
storage2 = {"mango": 10, "grapes": 20, "orange":30 }
Use the for loop to iterate all the keys present in the storage2, Take the keys from the storage to and check if the key is present in the storage one if so you found unique key, combine the values of unique key Use the else block signifying that you didn't find a matching keys, so just move the values of storage2 to storage1
for item in storage2.keys():
if item in storage1.keys():
storage1[item] += storage2[item]
else:
storage1[item] = storage2[item]
Use print function call to print the final storage1 dictionary.
print("Dictionary After Combining is ...")
for key, value in storage1.items():
print(key, value)
Complete Python Code :
storage1 = {"apple": 10, "orange": 20, "banana":30, "strawberry":40 }
storage2 = {"mango": 10, "grapes": 20, "orange":30 }
for item in storage2.keys():
if item in storage1.keys():
storage1[item] += storage2[item]
else:
storage1[item] = storage2[item]
print("Dictionary After Combining is ...")
for key, value in storage1.items():
print(key, value)
Output :
Dictionary After Combining is ...
apple 10
orange 50
banana 30
strawberry 40
mango 10
grapes 20
Output :
Conclusion :
The above Python program Text to dictionary variable containing the existing elements as fruits.
The two dictionary data structure has one common key (orange) and different value, so the resulting dictionary will contain values added for common keys.
Comment it down below if you have any suggestions to improve the above Python program
0 Comments