遍历python字典的键,当键是整数时,我得到这个错误,"TypeError: argument of type 'int' is not iterable"



我正在研究具有特定idsemployeespay raise。假设,我的公司有5名员工。我已经在employee_id_list中展示了它们.我希望python从我那里获得输入,其中包括employees的特定ids,我想提高工资以及他们的salary。然后,我正在根据这些输入创建dictionary。现在我想迭代employee_id_list,使其与input ids匹配。如果匹配,我想采取相应的value of keysalary并提高工资。但是我收到一个错误。 我已经搜索了堆栈溢出上存在的所有内容,但没有任何东西与我的问题匹配

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

将@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] = 1.8*value
print(employee_dict)

是这样的:

if e_ids in employee_dict[key] :

employee_dict是一个字符串-整数对的字典,您正在尝试检查e_ids是否在employee_dict[key]中,这是一个int,而不是像列表那样的可迭代对象,您可以在其中检查元素是否包含在其中。

另外,你不是说employee_dict[key] = 0.8*value + value吗?

你混淆了key和 for 循环value变量

试试这个:

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

相关内容

最新更新