CBSE Class 12 Computer Science Question 48 of 57

Review of Python Basics — Question 48

Back to all questions
48
Question

Question 43

Write a Python program to combine two dictionaries adding values for common keys.

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

Sample output:

Counter({'a': 400, 'b': 400, 'c': 300, 'd': 400})
Solution
d1 = {'a': 100, 'b': 200, 'c': 300}
d2 = {'a': 300, 'b': 200, 'd': 400}
combined_dict = {}
for key, value in d1.items():
    combined_dict[key] = value
for key, value in d2.items():
    if key in combined_dict:
        combined_dict[key] += value
    else:
        combined_dict[key] = value

print("Combined dictionary with added values for common keys:", combined_dict)
Output
Combined dictionary with added values for common keys: {'a': 400, 'b': 400, 'c': 300, 'd': 400}
Answer

d1
=
{
'a'
:
100
,
'b'
:
200
,
'c'
:
300
}
d2
=
{
'a'
:
300
,
'b'
:
200
,
'd'
:
400
}
combined_dict
=
{}
for
key
,
value
in
d1
.
items
():
combined_dict
[
key
]
=
value
for
key
,
value
in
d2
.
items
():
if
key
in
combined_dict
:
combined_dict
[
key
]
+=
value
else
:
combined_dict
[
key
]
=
value
print
(
"Combined dictionary with added values for common keys:"
,
combined_dict
)
Output
Combined dictionary with added values for common keys: {'a': 400, 'b': 400, 'c': 300, 'd': 400}