Skip to main content

How to Add User Input to Dictionaries in Python

This guide explores various methods for adding user input to dictionaries in Python. We'll cover creating dictionaries from separate key and value inputs, handling potential errors, preventing duplicate keys, and using split() for more flexible input formats.

Adding User Input with a for Loop

The most basic approach is to use a for loop to repeatedly prompt for keys and values:

employees = {}

for i in range(3):
name = input("Enter employee's name: ")
salary = input("Enter employee's salary: ")
employees[name] = salary # Add key-value pair

print(employees)

Example:

Enter employee's name: Alice
Enter employee's salary: 100
Enter employee's name: Anna
Enter employee's salary: 150
Enter employee's name: Carl
Enter employee's salary: 200
{'Alice': '100', 'Anna': '150', 'Carl': '200'}
  • The for loop with range(3) will repeat the prompting and adding process three times.

Converting Input to Integers

If you need numeric values (like integers), use int() to convert the input strings:

employees = {}
# ... (rest of the loop)
salary = int(input("Enter employee's salary: ")) # convert string to an integer
employees[name] = salary
note

Always validate user input, handling non-numeric values gracefully.

Preventing Duplicate Keys

Dictionaries can not have duplicate keys. To prevent overwriting existing entries, check if a key already exists before adding it:

employees = {}
max_length = 3

while len(employees) < max_length:
name = input("Enter employee's name: ")
if name not in employees: # Check for key existence
salary = input("Enter employee's salary: ")
employees[name] = salary
else:
print(f"An employee with the name '{name}' already exists.")

print(employees)
  • The while len(employees) < max_length: will continue to prompt for input, until there are max_length key-value pairs in the dictionary.
  • The if name not in employees will check that no duplicate keys are introduced.

Adding User Input with split()

You can allow users to enter key-value pairs on a single line, separated by spaces or commas, and then use split() to parse the input.

Using a space as separator

employees = dict(
input('Enter key and value separated by space: ').split()
for _ in range(2))
print(employees)

Example

Enter key and value separated by space: id 1
Enter key and value separated by space: name Alice
{'id': '1', 'name': 'Alice'}
  • The split() method, with no separator, will create a list, separating the values by any whitespace.

Using a comma as separator

You can change the separator by passing in a string delimiter to the split() method:

employees = dict(
input('Enter key and value separated by comma: ').split(',')
for _ in range(2))
print(employees)

Example

Enter key and value separated by comma: id,1
Enter key and value separated by comma: name,Alice
{'id': '1', 'name': 'Alice'}

Input Validation (Important)

Always validate user input to prevent errors and ensure data integrity. Here's a more robust example that handles potential ValueError exceptions and checks for empty input.

def get_valid_salary():
"""Gets a valid salary input from the user."""
while True:
try:
salary_str = input("Enter employee's salary: ").strip()
if not salary_str:
print("Salary can not be empty.")
continue # Go back to the beginning of the loop
salary = int(salary_str) # Try to convert to integer
if salary < 0:
print("Salary can't be negative.")
continue
return salary # Valid input
except ValueError:
print("Invalid salary. Please enter a valid integer.")

employees = {}
max_length = 3
while len(employees) < max_length:
name = input("Enter employee's name: ").strip()
if not name:
print("Name can not be empty")
continue
if name in employees:
print("Employee with that name already exists.")
continue

salary = get_valid_salary()
employees[name] = salary

print(employees)
  • This code uses the get_valid_salary() function which will continue to ask the user for input until a non-negative integer is entered.
  • The strip() method is used for preventing users to enter empty values.
  • This complete example includes input validation for both name and salary, preventing empty inputs, duplicate names, and non-integer salaries.

Adding User Input with a while Loop

You can use a while loop to keep collecting data from the user until a condition is met:

    employees = {}
while len(employees) < 3:
name = input("Enter employee's name: ")
salary = input("Enter employee's salary: ")
employees[name] = salary
print(employees)

Example:

Enter employee's name: Anna
Enter employee's salary: 200
Enter employee's name: Alice
Enter employee's salary: 400
Enter employee's name: Carol
Enter employee's salary: 600
{'Anna': '200', 'Alice': '400', 'Carol': '600'}
  • The while loop keeps going for as long as the length of the dictionary employees is less than 3.
  • Then user input for keys and values is collected, and the dictionary is constructed from the entered pairs.