Search code examples
python-3.xdictionaryflaskget

Traversing Multiple Levels of Dictionaries in Python


Let's say there's a schedules dictionary:

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"}
                    }
                }
            }
        }
}

And there is a Flask route that is supposed to grab a specific month's schedule, for example getting a GET request with request.args.get("months") = "aug" . I have tried the following:

 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)

Yet, the whole dictionary is returned for some reason. What exactly is missing here?


Solution

  • You're missing a few layers of the dictionary. You did not iterate over all the keys under 'employees' (the "1") and you did not iterate over all the months. This is what you can do:

    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)