CBSE Class 12 Computer Science Question 20 of 22

Python Revision Tour II — Question 10

Back to all questions
10
Question

Question 10

Write a function called addDict(dict1, dict2) which computes the union of two dictionaries. It should return a new dictionary, with all the items in both its arguments (assumed to be dictionaries). If the same key appears in both arguments, feel free to pick a value from either.

Solution
def addDict(dict1, dict2):
    union_dict = {}
    for key, value in dict1.items():
        union_dict[key] = value
    for key, value in dict2.items():
        union_dict[key] = value
    return union_dict

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
result = addDict(dict1, dict2)
print("Union of dict1 and dict2:", result)
Output
Union of dict1 and dict2: {'a': 1, 'b': 3, 'c': 4}
Answer

def
addDict
(
dict1
,
dict2
):
union_dict
=
{}
for
key
,
value
in
dict1
.
items
():
union_dict
[
key
]
=
value
for
key
,
value
in
dict2
.
items
():
union_dict
[
key
]
=
value
return
union_dict
dict1
=
{
'a'
:
1
,
'b'
:
2
}
dict2
=
{
'b'
:
3
,
'c'
:
4
}
result
=
addDict
(
dict1
,
dict2
)
print
(
"Union of dict1 and dict2:"
,
result
)
Output
Union of dict1 and dict2: {'a': 1, 'b': 3, 'c': 4}