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 program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...