Add user input to a dictionary in Python

avatar

Borislav Hadzhiev

Last updated: Jun 21, 2022

banner

Photo from Unsplash

Add user input to a dictionary in Python #

To add user input to a dictionary in Python:

  1. Declare a variable that stores an empty dictionary.
  2. Use a range to iterate N times.
  3. On each iteration, prompt the user for input.
  4. Add the key-value pair to the dictionary.
main.py
employees = {} for i in range(3): name = input("Enter employee's name: ") salary = input("Enter employee's salary: ") employees[name] = salary # 👇️ {'Alice': '100', 'Bob': '100', 'Carl': '100'} print(employees)

The code sample prompts the user for input 3 times and adds each key-value pair to the dictionary.

The example uses the range class, but you can also use a while loop if you want to make sure the dictionary has a length of at least N key-value pairs.

main.py
employees = {} max_length = 3 while len(employees) < max_length: name = input("Enter employee's name: ") salary = input("Enter employee's salary: ") employees[name] = salary # 👇️ {'Alice': '100', 'Bob': '100', 'Carl': '100'} print(employees)

If the dictionary has a length of less than 3, we keep prompting the user for input.

This approach is especially useful when you want to make sure the user doesn't enter the same key twice.

main.py
employees = {} max_length = 3 while len(employees) < max_length: name = input("Enter employee's name: ") salary = input("Enter employee's salary: ") # 👇️ check if key not in dict if name not in employees: employees[name] = salary # 👇️ {'Alice': '100', 'Bob': '100', 'Carl': '100'} print(employees)
We used an if statement to check if the key is not in the dictionary to avoid overriding the value of an existing key.

The in operator tests for membership. For example, k in d evaluates to True if k is a member of d, otherwise it evaluates to False.

k not in d returns the negation of k in d.

When used with a dictionary, the operators check for the existence of the specified key in the dict object.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.