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

In this sample program, you will learn how to insert a key-value pair to the dictionary and show it using the print() function.

To understand this demo program, you should have the basic Python programming knowledge.

However, here we’ll use the following steps to add a key-value pair to the dictionary.

  1. Get the key-value pair entered from the user and keep it them in different variables.
  2. Have a dictionary variable in your program and set it to a blank object.
  3. Call the update() method to insert the key-value pair to the dictionary.
  4. Print the dictionary variable.

Below is the sample code of the Python Program to add a key-value pair to the dictionary using the update() method.

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

You can use IDLE or any other Python IDE to create and execute the below program.

# Program to add a key-value pair to the dictionary

aKey = int(input("Enter a numeric key to insert in the dictionary:"))
aValue = int(input("Enter the value for the target key:"))
aDict = {}
aDict.update({aKey:aValue})
print("The dictionary after the update is as follows:")
print(aDict)

The output of the above code is as follows.

Use Case-1

Enter a numeric key to insert in the dictionary:10
Enter the value for the target key:100
The dictionary after the update is as follows:
{10: 100}

Use Case-2

Enter a numeric key to insert in the dictionary:100
Enter the value for the target key:10
The dictionary after the update is as follows:
{100: 10}