How to Add user input to a Dictionary in Python

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
4 min

banner

# 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)

add user input to dictionary

The code for this article is available on GitHub

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 to prompt the user for key-value pairs.

The range class is commonly used for looping a specific number of times in for loops

If you only pass a single argument to the range() constructor, it is considered to be the value for the stop parameter.

main.py
print(list(range(3))) # [0, 1, 2] print(list(range(5))) # [0, 1, 2, 3, 4]

The range starts at 0 and goes up to, but not including the specified number.

Note that the input() function always returns a value of type string.

If you need to add an integer value to the dictionary, use the int() class to convert the string to an integer.

main.py
employees = {} # ๐Ÿ‘‡๏ธ converting to integer with int() salary = int(input("Enter employee's salary: ")) employees['salary'] = salary # ๐Ÿ‘‡๏ธ {'salary': 100} print(employees)

# Add user input to a dictionary using a while loop

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)

add user input to dictionary

The code for this article is available on GitHub

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

# Preventing the user from adding the same key to the dictionary

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 the key not in the dict if name not in employees: employees[name] = salary # ๐Ÿ‘‡๏ธ {'Alice': '100', 'Bob': '100', 'Carl': '100'} print(employees)

prevent user from adding same key twice

The code for this article is available on GitHub
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.

main.py
my_dict = { 'id': 1, 'name': 'Bobby Hadz', 'salary': 500, } print('name' in my_dict) # ๐Ÿ‘‰๏ธ True print('another' in my_dict) # ๐Ÿ‘‰๏ธ 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.

Want to learn more about taking input from the user in Python? Check out these resources: How to take a List from user input in Python,Multiple lines user Input in Python,How to Validate user input in Python.

# Add user input to a dictionary using split()

You can also use the str.split() method to add user input to a dictionary.

main.py
employees = dict( input('Enter key and value separated by space: ').split() for _ in range(2)) # ๐Ÿ‘‡๏ธ {'id': '1', 'name': 'Alice'} print(employees)

using split to take dictionary input

The code for this article is available on GitHub

The example expects that the user enters space-separated keys and values.

main.py
print('name Alice'.split()) # ['name', 'Alice']

The str.split() method splits the string into a list of substrings using a delimiter.

The method takes the following 2 parameters:

NameDescription
separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt most maxsplit splits are done (optional)

We used a space separator in the example, but you can also use a comma if the values of the dictionary contain spaces.

main.py
employees = dict( input('Enter key and value separated by space: ').split(',') for _ in range(2)) # ๐Ÿ‘‡๏ธ {'id': '1', 'name': 'Alice'} print(employees)

using split with comma to add input to dictionary

The code for this article is available on GitHub

The code sample is similar to the previous one, however, we used a comma as the separator instead of a space.

This is useful because the values of the dictionary might contain spaces.

I've written a detailed guide on converting a comma-separated string to a dictionary in Python.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev