Python Program to add a key-value pair to dictionary

In this simple python program, we need to add a key-value pair to a dictionary. It is a number-based python program.

For a better understanding of this example, we always recommend you to learn the basic topics of Python programming listed below:

What is a dictionary in python?

The Dictionary is a collection of values that is unordered and has a key and value pair. We use the dictionary to retrieve the Value easily when we know the Key.

We can add the elements into a python dictionary using the braces. We put the elements in the braces with a comma. Every element in the dictionary has a key and a value that is associated with the key represented as a key-value pair. 

Values may be of any value or any type which may be a repeat or not, but for a key, it must not be a repeat, and it must be a tuple, number, or string.

How do we add key-value pairs in the python dictionary?

In this simple python program, we accept the number for the key and the value from the user using the input function and save that into a variable using int data type. Declare a dictionary and initialize it to zero using the braces. Then we update the dictionary with the values we got from the user. Finally, we print the dictionary, key, and value pair using the simple python language's print function.

ALGORITHM

STEP 1: Accept the values from for key and value from the user using input and int in python language.

STEP 2: Declare and initialize the dictionary with zero elements.

STEP 3: Update the elements of the dictionary with the key and value from the user.

STEP 4: Print the dictionary and the key and value using the print statement.

Python Source Code

                                          key=int(input("Enter the key:"))
value=int(input("Enter a value for key:"))
d={}
d.update({key:value})
print("Dictionary is Upt odate with value:")
print(d)
                                      

OUTPUT

Enter the key: 10
Enter a value for key: 50
Dictionary is Up to date with value:
{10: 50}