How can I use the append function to make a list of dictionaries in a list of dictionaries

Question:

I have a dictionary consisting of four parameters: teacher, day, time, and subject. When I write them to a JSON file, they look like this:

[
    {"day": "Monday",
    "lesson": "Math",
    "teacher": "Mr John",
    "time": "8:00"},
    {"day": "Monday",
     "lesson": "Math",
     teacher": "Mr John",
     "time": "9:00"},
    ...
    ]

But I need to make a dictionary list in the dictionary list so that the JSON file looks like this:

[
    {"teacher": "Mr John",
    lessons:[
    {"day": "Monday",
    "time": "8:00",
    "lesson: "Math"},
    {"day": "Monday",
    "time": "9:00",
    "lesson: "Math"},
    ...
    ]}]

I tried the following code:

 lst = []
    my_list = []
    my_dict = {"teacher": "Mr John",
    "lessons":
    my_list.append(
    {"day": "Monday",
    "time": "8:00",
    "lesson": "Math"},
    {"day": "Monday",
    "time": "9:00",
    "lesson": "Math"},
    )
    }
    lst.append(my_dict)
    lst.append(my_list)
    with open("schedule.json", "w", encoding='utf-8') as json_file:
        json.dump(lst, json_file, indent=4, sort_keys=True, ensure_ascii=False)

That’s what I get:

[
    {"lessons": null,
    "teacher": "Mr John"},
    [
    {"day": "Monday",
    "lesson": "Math",
    "time": "8:00"}
    ],
    {"lessons": null,
    "teacher": "Mr John"},
    [
    {"day": "Monday",
    "lesson": "Math",
    "time": "9:00"}
    ]

The teacher is constantly being written again instead of once, the value lessons are empty, and each lesson is written to a new array.
How do I fix/write the code so that I get the JSON file I need? I’m sorry if there was such a question already; I’m super new to this site and Python. Thank you in advance for your answers!

Asked By: Errorerere

||

Answers:

You will need to update this portion, like so

lst = []
my_dict = {"teacher": "Mr John", "lessons": []}
my_dict["lessons"].append({"day": "Monday", "time": "8:00", "lesson": "Math"})
my_dict["lessons"].append({"day": "Monday", "time": "9:00", "lesson": "Math"})
lst.append(my_dict)

with open("schedule.json", "w", encoding='utf-8') as json_file:
    json.dump(lst, json_file, indent=4, sort_keys=True, ensure_ascii=False)
Answered By: Anthony Tuccitto
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.