Home > front end >  adding to dict variable in list of dicts
adding to dict variable in list of dicts

Time:10-13

I have a list of dicts like this:

students=
    [
    {rollno:1,firstname:f1,last_name:l1,total_marks:0},
    {rollno:2,firstname:f2,last_name:l2,total_marks:0},
    {rollno:3,firstname:f3,last_name:l3,total_marks:0}
    ]

Then I get input in a loop in the form of

    rollno:1 english_marks:10
    rollno:2 english_marks:20
    rollno:5 social_marks: 30
    rollno:6 maths_marks:40
    rollno:1 science_marks:30
    rollno:2 science_marks:40

Now I want to add all subject marks related to correct roll number total_marks variable. How can I achieve this?

for marks in marks_list:
   students[rollno] = ...?  # need help here : how can I access total_marks variable of that rollno?

CodePudding user response:

Because students is a list, with no key, you can't index it with anything other than an int, which doesn't help you if you are trying to use the rollno as a key. Assuming you want to use the data structures you've shown (and not create new data structures,) you must loop over the list of students to find the one with the rollno you want.

for marks in marks_list:
  for student in students:
    if student[rollno] == marks[rollno]:
       # you found the student whose rollno matches that of the mark, so do your stuff here

There are other ways to do this with shorthand, find, etc. but since you say you are new to Python, I think it's best to see the raw loops doing the work.

Note that you should never modify any collection while looping over it. So be sure to create a copy or new list if you want to save any mutations of the data.

CodePudding user response:

You're probably looking for something similar to this, assuming your students object and a list of tuples (i.e. (1, "maths_mark", 90)) names marks_list:

# Set up your basic data structure
student_roll = {r.get("rollno"): {
    "firstname": r.get("firstname", "unknown"),
    "lastname": r.get("lastname", "unknown"),
    "total_marks": 0,
    "marks": {}
} for r in students}

# Convert your values into that structure
for (roll_no, mark, score) in marks_list:
    roll = students_roll.get(roll_no)
    marks = roll.get("marks", {})
    score_list = marks.get(mark, [])
    score_list.append(score)
    marks[mark] = score_list
    # do the appropriate math to update r[total_marks] = ...
    student_roll[roll_no] = roll

This will produce a dictionary that looks something like:

{
  1: {
    "firstname": "Joe",
    "lastname": "DeFalt",
    "total_marks": 20,
    "marks": {
      "english_marks": [10, 20],
      "math_marks": [30]
    },
  2: {
    "firstname": "Jessica",
    "lastname": "Bambino",
    "total_marks": 90,
    "marks": {
      "social_marks": [100, 70],
      "math_marks": [100]
    },
}
  • Related