Python函数循环字典

时间:2017-10-31 01:15:56

标签: 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])
        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

1 个答案:

答案 0 :(得分:1)

我认为您只想打印,一旦return它返回要返回的内容并结束该功能。此外,您不需要设置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"])