
PRO
Shawn
asked

Expert
Abhay Jajodia answered
To add items to a dictionary, you can use dictionary assignment. Here’s a simple explanation:
Steps to Add Key-Value Pairs to a Dictionary
Create an Empty Dictionary: Start with an empty dictionary using
{}.my_dict = {}Define Your Loop: Use a
forloop to iterate a set number of times, asking the user for key-value pairs.for i in range(3): # This loop will run three timesGet User Input for Key and Value: During each iteration, prompt the user for a key and a value.
key = input("Enter the key: ") value = input("Enter the value: ")Add the Key-Value Pair to the Dictionary: Use assignment to add them to the dictionary.
my_dict[key] = valuePrint the Dictionary: Once you’ve added all key-value pairs, print the dictionary to see the result.
print(my_dict)
Here’s how your code might look after incorporating these elements:
# create an empty dictionary named my_dict
my_dict = {}
# use for loop to iterate and gather user input
for i in range(3):
key = input("Enter the key: ")
value = input("Enter the value: ")
my_dict[key] = value # add the key-value pair to the dictionary
# print the final dictionary
eprint(my_dict)
I hope this clears things up! Feel free to ask any follow-up questions if you need more clarification. 😊
Python
This question was asked as part of the Practice: Python Basics course.
Our Experts
Sudip BhandariHead of Growth/Marketing
Apekchhya ShresthaSenior Product Manager
Kelish RaiTechnical Content Writer
Abhilekh GautamSystem Engineer
Palistha SinghTechnical Content Writer
Sarthak BaralSenior Content Editor
Saujanya Poudel
Abhay Jajodia
Nisha SharmaTechnical Content Writer
Udayan ShakyaTechnical Content Writer