Write A Python Script To Add Key To A Dictionary

Let's write a python script to add a key and value pair to a given dictionary. As an input from the user I will be defining a dictionary and asking a user to enter the dictionary items that are key value pairs.  finally display the contents of the dictionary using the.

This Python dictionary is generic. You can use it for multipurpose By modifying the key value type. I will be using the key as a string type and the value is an integer type.

 

Write A Python Script To Add Key To A Dictionary

 



Write A Python Script To Add Key To A Dictionary

Let's take an integer variable named length and use the input function call as a user to enter a dictionary and then convert it into an integer using the  type conversion.  take another variable named as dictionary and initialize it to an Empty dictionary.


length = int(input("Enter Dictionary Length : "))
dictionary = {}





Using the for loop iterate from 0 to the dictionary length and ask a user to enter the dictionary key value pair.  once the user enters the key value pair appended to the dictionary as shown below

for _ in range(length):
   key = input("Enter Dictionary Key (string) : ")
   value = int(input(f"Enter Dictionary Integer Value for {key} : "))
   dictionary[key] = value





Using the print statement print the contents of of the dictionary,  use another  for loop and iterate the key value pair of the dictionary and print it

print("The contents of the dictionary after adding the key value pair is ...")
for key, value in dictionary.items():
   print(f"{key} : {value}")





Python code
====================

length = int(input("Enter Dictionary Length : "))
dictionary = {}

for _ in range(length):
   key = input("Enter Dictionary Key (string) : ")
   value = int(input(f"Enter Dictionary Integer Value for {key} : "))
   dictionary[key] = value


print("The contents of the dictionary after adding the key value pair is ...")
for key, value in dictionary.items():
   print(f"{key} : {value}")






Output
===============
Enter Dictionary Length : 5
Enter Dictionary Key (string) : apple
Enter Dictionary Integer Value for apple : 123
Enter Dictionary Key (string) : orange
Enter Dictionary Integer Value for orange : 50
Enter Dictionary Key (string) : grapes
Enter Dictionary Integer Value for grapes : 30
Enter Dictionary Key (string) : banana
Enter Dictionary Integer Value for banana : 80
Enter Dictionary Key (string) : strawberry
Enter Dictionary Integer Value for strawberry : 400
The contents of the dictionary after adding the key value pair is ...
apple : 123
orange : 50
grapes : 30
banana : 80
strawberry : 400





Conclusion
==================
 execute the above Python program by providing the key value pair as an input to the dictionary and then down the result.


 comment down below if you have any suggestions to optimize the above Python programá¹£



Post a Comment

0 Comments