Borislav Hadzhiev
Last updated: Jun 21, 2022
Photo from Unsplash
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, 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.
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 key not in 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
.
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.