How To Store Multiple User Input In Dictionary Python

In this tutorial, we will learn how to store multiple user inputs in a dictionary in Python. Dictionaries are a versatile and efficient way of storing and organizing data in key-value pairs.

They allow you to easily access, update or delete the data as required. Storing user inputs in dictionaries can help you manage and process the input data more efficiently.

Step 1: Initialize an empty dictionary

To store user inputs, first, we need to initialize an empty dictionary. You can create an empty dictionary using the below syntax:

Step 2: Take user input

Next, we need to take user input. This can be done using the input() function, which reads a line from the standard input (keyboard) and converts it to a string.

For example, to take input for the ‘name’ and ‘age’ fields, you can use the following code snippet:

Here, we have used int() to convert the age input into an integer value.

Step 3: Add input to the dictionary

After taking the user input, the next step is to add the input data to the dictionary we initialized in Step 1. You can do this using the following syntax:

Now, the user data has been added to the dictionary with the keys ‘name’ and ‘age’, and their respective values.

Step 4: Repeat the process for multiple users

To store input data for multiple users, you can repeat the process explained above using a loop. For example, here we will use a for loop to take input from three users:

In this example, we have used the user’s name as the key and the user’s age as the value for the dictionary. After running this script, the user_data dictionary will contain the input data of all three users.

Step 5: Print the user data

Finally, after taking input from users and storing it in the dictionary, you can print the user data using the print() function:

Full code:

Output:

Please enter the name of user 1: John
Please enter the age of user 1: 25
Please enter the name of user 2: Mary
Please enter the age of user 2: 32
Please enter the name of user 3: Mike
Please enter the age of user 3: 40
User data:  {'John': 25, 'Mary': 32, 'Mike': 40}

Conclusion

In this tutorial, we have learned how to store multiple user inputs in a dictionary in Python. This method can be used to efficiently store and manage user inputs for various applications. You can further improve this code by adding error handling, validating user inputs, or using more complex data structures depending on your requirements.