Итерация по ключам словаря, когда ключи целые, теперь я получаю эту ошибку "TypeError: argument of type 'int' is not iterable".
Я работаю над pay raise из employees с определенным ids. Предположим, в моей компании есть 5 сотрудников. Я отобразил их в employee_id_list. Я хочу, чтобы python принимал от меня входные данные, состоящие из конкретных ids сотрудников employees, которым я хочу повысить зарплату, вместе с их salary. Затем я создаю dictionary из этих входных данных. Теперь я хочу выполнить итерацию по employee_id_list так, чтобы он совпадал с input ids. Если он совпадает, я хочу взять соответствующий value of key, который является salary, и повысить зарплату. Но я получаю ошибку.
Я просмотрел все, что есть на stackoverflow, но ничего не подходит к моей проблеме
employee_id_list = [27, 25, 98, 78, 66]
employee_dict = dict()
while True:
x = input("Enter an key to continue and 'r' for result: ").lower()
if x== 'r':
break
try:
employee_id = int(input("Enter key the Employee id: "))
salary = int(input(f"Enter the {employee_id}'s salary: "))
employee_dict[employee_id] = salary
except ValueError:
print("Please Enter the Integers!")
continue
print(employee_dict)
for e_ids in employee_id_list:
for key, value in employee_dict.items():
if e_ids in employee_dict[key] :
employee_dict[value] = 0.8*value + value
print(employee_dict)
Я получаю эту ошибку
TypeError: argument of type 'int' is not iterable
Это:
if e_ids in employee_dict[key] :
employee_dict - это словарь пар строка-целое число, и вы пытаетесь проверить, находится ли e_ids в employee_dict[key], который является int, а не итерабельным, как список, где вы можете проверить, содержится ли элемент в нем.
Также, разве вы не имеете в виду employee_dict[key] = 0.8*value + value?
Вы путаете переменные key и value цикла for
Попробуйте это:
employee_id_list = [27, 25, 98, 78, 66]
employee_dict = dict()
while True:
x = input("Enter an key to continue and 'r' for result: ").lower()
if x == 'r':
break
try:
employee_id = int(input("Enter key the Employee id: "))
salary = int(input(f"Enter the {employee_id}'s salary: "))
employee_dict[employee_id] = salary
except ValueError:
print("Please Enter the Integers!")
continue
for e_ids in employee_id_list:
for key, value in employee_dict.items():
if e_ids in employee_dict:
employee_dict[key] = 0.8*value + value
print(employee_dict)
Вы должны написать employee_dict[key] = 0.8*value+value, а не employee_dict[value] = 0.8*value+value.
Вы также можете написать employee_dict[key] = value*1.8, а не employee_dict[key] = 0.8*value+value.
Соединив правильные идеи @Konny и @Sunderam вместе, и добавив мое собственное изменение для проверки оператора if, ответ будет таким:
employee_id_list = [27, 25, 98, 78, 66]
employee_dict = dict()
while True:
x = input("Enter an key to continue and 'r' for result: ").lower()
if x== 'r':
break
try:
employee_id = int(input("Enter key the Employee id: "))
salary = int(input(f"Enter the {employee_id}'s salary: "))
employee_dict[employee_id] = salary
except ValueError:
print("Please Enter the Integers!")
continue
print(employee_dict)
for e_ids in employee_id_list:
for key, value in employee_dict.items():
if e_ids == key: # This is my contribution
employee_dict[key] = 0.8*value + value
print(employee_dict)