How To Get Dictionary Values From User In Python

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:

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.

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.

Step 4: Display the completed dictionary

After gathering the user’s input, display the dictionary with its key-value pairs.

Full code:

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'}


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.