Python函数循环字典
我试图以特定的格式输出员工信息 dep_tup是一个包含所有不同部门名称的元组,用户输入的名称不重复 dep_dict是一个字典,其中部门作为键,满列表的员工字典作为与键关联的值Python函数循环字典,python,python-3.x,file,dictionary,Python,Python 3.x,File,Dictionary,我试图以特定的格式输出员工信息 dep_tup是一个包含所有不同部门名称的元组,用户输入的名称不重复 dep_dict是一个字典,其中部门作为键,满列表的员工字典作为与键关联的值 #Function that outputs the employees by department def deps(): for department in dep_tup: i = 0 total = len(dep_dict[department]) fo
#Function that outputs the employees by department
def deps():
for department in dep_tup:
i = 0
total = len(dep_dict[department])
for i in range(len(dep_dict[department])):
return "%s with %d employees\n" % (dep_dict[department], total)
return "\n%s: %s, %s, $%f per year\n" % (dep_dict[department][i]["name"], dep_dict[department][i]["position"], dep_dict[department][i]["em_department"], dep_dict[department][i]["salary"])
i += 1
例如,如果用户输入1名来自销售部门的员工和1名来自运营部门的员工,则应输出如下内容:
#Sales with 1 employees
#John Doe: sales lead, sales, $50000.00 per year
#Operations with 1 employees
#Jane Doe: technician, operations, $60000.00 per year
我认为您只想打印,一旦返回,它将返回要返回的内容并结束函数。此外,您不需要设置i并将其递增,因为for循环会自动这样做。以下应该可以工作,但如果没有提供初始输入,我不能确定
def deps():
for department in dep_tup:
total = len(dep_dict[department])
for i in range(len(dep_dict[department])):
print("%s with %d employees\n" % (dep_dict[department], total))
print("\n%s: %s, %s, $%f per year\n" % (dep_dict[department][i]["name"], dep_dict[department][i]["position"], dep_dict[department][i]["em_department"], dep_dict[department][i]["salary"])
你不必连续返回语句…是的,那太完美了!我只需要把第一行打印在for循环的顶部,这样它就不会在同一个部门重复该语句了!但我的部门主管正在打印与该部门相关的全部清单。我怎么能打印部门名称呢?我得看看你的字典才能帮上忙