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

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:

  1. The add_key_value function takes three parameters: dictionary, key, and value.
  2. Inside the function, it adds the new key-value pair to the provided dictionary using the given key and value.
  3. The program starts with an existing dictionary named my_dictionary.
  4. The user is prompted to input a new key and a new value.
  5. The add_key_value function is called to add the new key-value pair to the my_dictionary.
  6. Finally, the updated dictionary is printed.

Input/Output:

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

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this python tutorial, you will learn how to Display Prime Numbers Between Two Intervals using the if and else...
In this python tutorial, you will learn how to Calculate Standard Deviation with built in functions of the python programming...
In this Python program, we will convert temperature values from Celsius to Fahrenheit. The Celsius and Fahrenheit scales are two...