Shawn Sivakumar
PRO
last year
Shawncountry asked

I do not know how to add stuff in dictionaries.

Abhay Jajodia
Expert
last year
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

  1. Create an Empty Dictionary: Start with an empty dictionary using {}.

    my_dict = {}
  2. Define Your Loop: Use a for loop to iterate a set number of times, asking the user for key-value pairs.

    for i in range(3): # This loop will run three times
  3. Get 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: ")
  4. Add the Key-Value Pair to the Dictionary: Use assignment to add them to the dictionary.

    my_dict[key] = value
  5. Print 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.