Friday 1 January 2021

Python Program to Concatenate Two Dictionaries Into One

 This is a Python Program to concatenate two dictionaries into one dictionary.

Problem Description

The program takes two dictionaries and concatenates them into one dictionary.

Problem Solution

1. Declare and initialize two dictionaries with some key-value pairs
2. Use the update() function to add the key-value pair from the second dictionary to the first dictionary.
3. Print the final dictionary.
4. Exit.

Program/Source Code

Here is source code of the Python Program to add a key-value pair to a dictionary. The program output is also shown below.

d1={'A':1,'B':2}
d2={'C':3}
d1.update(d2)
print("Concatenated dictionary is:")
print(d1)
Program Explanation

1. User must enter declare and initialize two dictionaries with a few key-value pairs and store it in separate variables.
2. The update() function is used to add the key-value pair from the second to the first dictionary.
3. The final updated dictionary is printed.

Runtime Test Cases
 
Case 1:
Concatenated dictionary is:
{'A': 1, 'C': 3, 'B': 2}

No comments:

Post a Comment