Giving a dictionary as input in Python is a very common and useful way to provide a structured collection of data elements consisting of key-value pairs.
The Python dictionary is a built-in fundamental data structure that allows you to store and access an information set, wherein, each item has a unique identifying key.
This tutorial will guide you through the process of giving a dictionary as input in Python step-by-step.
Step 1: Initialize an empty dictionary
First, let’s create an empty dictionary to later add elements to it.
1 2 |
# Initialize an empty dictionary my_dict = {} |
Step 2: Accept key-value pairs from the user
Next, we define the number of key-value pairs to be added to the dictionary and then prompt the user to provide these pairs. We will be using a for loop to iterate through the process of collecting inputs and adding them to the dictionary.
1 2 3 4 5 6 7 8 |
# Get the number of key-value pairs from the user n = int(input("Enter the number of elements you want to add to the dictionary: ")) # Collect key-value pairs from the user for i in range(n): key = input("Enter the key: ") value = input("Enter the value: ") my_dict[key] = value |
Step 3: Display the dictionary
Finally, let’s display the resulting dictionary.
1 |
print("The dictionary is:", my_dict) |
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Initialize an empty dictionary my_dict = {} # Get the number of key-value pairs from the user n = int(input("Enter the number of elements you want to add to the dictionary: ")) # Collect key-value pairs from the user for i in range(n): key = input("Enter the key: ") value = input("Enter the value: ") my_dict[key] = value # Display the dictionary print("The dictionary is:", my_dict) |
Example Output
Enter the number of elements you want to add to the dictionary: 3 Enter the key: name Enter the value: John Enter the key: age Enter the value: 25 Enter the key: occupation Enter the value: Developer The dictionary is: {'name': 'John', 'age': '25', 'occupation': 'Developer'}
Conclusion
In this tutorial, we went through the process of giving a dictionary as input in Python. You can easily modify the code to suit your specific requirements by adding more validation or type casting when collecting the inputs from the user. The power of Python dictionaries makes it an invaluable tool for working with structured data, and now you know how to obtain them from user inputs.