Mee Seong Im
Mee Seong Im

Reputation: 141

Lists in n dictionaries in a list

This is a small project that I'm working on but I'm a bit stuck with the following portion of my code.

As you can see, j is a dictionary which represents a student's grades. I would like j to vary from 1 to n, where n is the total number of students in a class, but because each dictionary (corresponding to each student) doesn't have a distinct name, the code starting with "while grades in yes" is attaching each student's grade to all the ex or hw values of every dictionary (except the dictionary corresponding to model).

What's the best way to modify j so that I can input n students in unique_id?

Edit: I could replace j with j_one, j_two, etc and copy and paste the "empty" dictionary but I think this is too much work if you have, say, 280 students (hypothetically speaking).

unique_id = [] 

model = {                    
    "Last": "Total",     
    "First": "Possible on",
    "id": "000000",
    "ex": [],
    "hw": []
    }
unique_id.append(dict(model))

yes = {"yes", "ye", "y"}
ex = {"ex", "e", "exam"}
hw = {"hw", "h", "homework"}

j ={
    "Last": "",     
    "First": "",
    "id": "",
    "ex": [],
    "hw": []
}

new_person = input("New student? Type YES or NO. ").lower()

while new_person in yes:   
    j["Last"] =  input("Last Name: ")    
    j["First"] = input("First Name: ")
    j["id"] = input("ID: ")
    unique_id.append(dict(j)) 
    new_person = input("New student? Type YES or NO. ").lower()

grades = input("Input grades? ").lower()

while grades in yes:
    option_grades = input("Pick EX, HW: ").lower()
    if option_grades in ex:
        for i in list(range(len(unique_id))):
            unique_id[i]["ex"].append(input("%s %s Exam: " % (unique_id[i]["Last"], unique_id[i]["First"])))
    elif option_grades in hw:
        for i in list(range(len(unique_id))):
            unique_id[i]["hw"].append(input("%s %s HW: " % (unique_id[i]["Last"], unique_id[i]["First"]))) 


    grades = input("Input more grades? ").lower()

Upvotes: 1

Views: 48

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

You can create a template dict that will hold the relevant information, you can increment then add a template and increment the dict_id for each student.

 template ={
    "Last": "",
    "First": "",
    "id": "",
    "ex": [],
    "hw": []
}
j ={

}

new_person = input("New student? Type YES or NO. ").lower()
dict_id = 1
while new_person in yes:
    j[dict_id] = template # add new template for each student
    j[dict_id]["Last"] = input("Last Name: ")
    j[dict_id]["First"] = input("First Name: ")
    j[dict_id]["id"] = input("ID: ")
    unique_id.append(dict(j))
    new_person = input("New student? Type YES or NO. ").lower()
    dict_id += 1 # increment id

You may need to add more logic like maybe checking if the student is already in the dict etc.. but this should get you started.

Upvotes: 1

Related Questions