This python program demonstrates how to add a new key-value pair to an existing dictionary in Python.
Problem Statement:
You need to write a program that takes a key and a value as input and adds them as a new key-value pair to an existing dictionary.
Python Program to Add a Key-Value Pair to the Dictionary
def add_key_value(dictionary, key, value):
dictionary[key] = value
# Existing dictionary
my_dictionary = {'a': 1, 'b': 2, 'c': 3}
# Input
new_key = input("Enter the new key: ")
new_value = input("Enter the new value: ")
# Adding the key-value pair
add_key_value(my_dictionary, new_key, new_value)
# Output
print("Updated Dictionary:", my_dictionary)
How It Works:
- The
add_key_valuefunction takes three parameters:dictionary,key, andvalue. - Inside the function, it adds the new key-value pair to the provided dictionary using the given key and value.
- The program starts with an existing dictionary named
my_dictionary. - The user is prompted to input a new key and a new value.
- The
add_key_valuefunction is called to add the new key-value pair to themy_dictionary. - Finally, the updated dictionary is printed.
Input/Output:
