在Python中遍历字典的多个级别

时间:2018-08-14 22:58:42

标签: python-3.x dictionary flask get

假设有一个时间表字典:

schedules = {
        "employees": {
            "1":{
                "2018":{
                    "aug":{
                        "1": {"day": 1, "start": "08:00h"},
                        "2": {"day": 1, "start": "08:00h"}
                    },
                    "sep":{
                        "1": {"day": 1, "start": "08:00h"},
                        "2": {"day": 1, "start": "08:00h"}
                    }
                }
            }
        }
}

有一条Flask路线应该获取特定月份的时间表,例如使用request.args.get(“ months”)=“ aug”获取GET请求。我尝试了以下方法:

 sel_schedule = {}
    for employees, employee in schedules.items():
                for year, month in employee.items():
                    if month == request.args.get("months"):
                        sel_schedule = sel_schedule.update(month)
                        return render_template("scheduleinfo.html", sched = sel_schedule)

但是,由于某种原因,整个字典都被退回了。这里到底缺少什么?

1 个答案:

答案 0 :(得分:1)

您缺少字典的几层。您没有遍历'employees'"1")下的所有键,并且没有遍历所有月份。这是您可以做的:

for employees, employee in schedules.items():
    for num, schedule in employee.items():
        for year, months in schedule.items():
            for month in months:
                if month == request.args.get("months"):
                    sel_schedule.update(months[month])
                    return render_template("scheduleinfo.html", sched = sel_schedule)