Friday 1 January 2021

Python Program to Add a Key-Value Pair to the Dictionary

 This is a Python Program to add a key-value pair to a dictionary.

Problem Description

The program takes a key-value pair and adds it to the dictionary.

Problem Solution

1. Take a key-value pair from the user and store it in separate variables.
2. Declare a dictionary and initialize it to an empty dictionary.
3. Use the update() function to add the key-value pair to the dictionary.
4. Print the final dictionary.
5. 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.

key=int(input("Enter the key (int) to be added:"))
value=int(input("Enter the value for the key to be added:"))
d={}
d.update({key:value})
print("Updated dictionary is:")
print(d)
Program Explanation

1. User must enter a key-value pair and store it in separate variables.
2. A dictionary is declared and initialized to an empty dictionary.
3. The update() function is used to add the key-value pair to the dictionary.
4. The final dictionary is printed.

Runtime Test Cases
 
Case 1:
Enter the key (int) to be added:12
Enter the value for the key to be added:34
Updated dictionary is:
{12: 34}
 
Case 2:
Enter the key (int) to be added:34
Enter the value for the key to be added:29
Updated dictionary is:
{34: 29}

No comments:

Post a Comment