In this tutorial, you will learn how to get dictionary values from a user in Python. By the end of this tutorial, you will be able to prompt the user for key-value pairs, store them in a dictionary, and display the dictionary to the user.
Step 1: Initialize an empty dictionary
First, you need to initialize an empty dictionary that will store the user’s key-value pairs. To do this, enter the following code:
1 |
user_dictionary = {} |
Step 2: Prompt the user for the number of entries
Next, ask the user how many key-value pairs they would like to enter into the dictionary. Store the user’s input as an integer.
1 |
num_entries = int(input("Enter the number of entries you'd like to add: ")) |
Step 3: Get the user’s input for key-value pairs
Now, you will use a for
loop to prompt the user for their key-value pairs. The loop will iterate through the number of entries the user provided in the previous step. Inside the loop, ask the user for a key and a value, and then store them in the dictionary.
1 2 3 4 |
for i in range(num_entries): key = input("Enter key (string) for entry " + str(i + 1) + ": ") value = input("Enter value (string) for entry " + str(i + 1) + ": ") user_dictionary[key] = value |
Step 4: Display the completed dictionary
After gathering the user’s input, display the dictionary with its key-value pairs.
1 |
print("Your dictionary: ", user_dictionary) |
Full code:
1 2 3 4 5 6 7 8 9 10 |
user_dictionary = {} num_entries = int(input("Enter the number of entries you'd like to add: ")) for i in range(num_entries): key = input("Enter key (string) for entry " + str(i + 1) + ": ") value = input("Enter value (string) for entry " + str(i + 1) + ": ") user_dictionary[key] = value print("Your dictionary: ", user_dictionary) |
Example output:
Enter the number of entries you'd like to add: 2 Enter key (string) for entry 1: fruit Enter value (string) for entry 1: apple Enter key (string) for entry 2: vegetable Enter value (string) for entry 2: carrot Your dictionary: {'fruit': 'apple', 'vegetable': 'carrot'}
Conclusion
Now you know how to get dictionary values from a user in Python. By following these steps, you can create a simple script that allows users to input key-value pairs to build their own dictionary. This can be helpful for various applications, such as storing configuration settings, reading various parameters, or simply collecting basic data from the user.