Last updated: Apr 8, 2024
Reading timeยท4 min
To add user input to a dictionary in Python:
range
to iterate N times.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 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.
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.
employees = {} # ๐๏ธ converting to integer with int() salary = int(input("Enter employee's salary: ")) employees['salary'] = salary # ๐๏ธ {'salary': 100} print(employees)
while
loopYou can also use a while
loop if you want
to make sure the dictionary has a length of at least N key-value pairs.
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.
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)
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
.
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.
You can also use the str.split()
method to add user input to a dictionary.
employees = dict( input('Enter key and value separated by space: ').split() for _ in range(2)) # ๐๏ธ {'id': '1', 'name': 'Alice'} print(employees)
The example expects that the user enters space-separated keys and values.
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:
Name | Description |
---|---|
separator | Split the string into substrings on each occurrence of the separator |
maxsplit | At 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.
employees = dict( input('Enter key and value separated by space: ').split(',') for _ in range(2)) # ๐๏ธ {'id': '1', 'name': 'Alice'} print(employees)
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.
You can learn more about the related topics by checking out the following tutorials: