Home > front end >  Iterate over List of List to Get Dictionary
Iterate over List of List to Get Dictionary

Time:09-02

INPUT:

grades = [
    # First line is descriptive header. Subsequent lines hold data
    ['Student', 'Exam 1', 'Exam 2', 'Exam 3'],
    ['Thorny', '100', '90', '80'],
    ['Mac', '88', '99', '111'],
    ['Farva', '45', '56', '67'],
    ['Rabbit', '59', '61', '67'],
    ['Ursula', '73', '79', '83'],
    ['Foster', '89', '97', '101']
]

Required Output:

{'Exam 1': [100, 88, 45, 59, 73, 89],
 'Exam 2': [90, 99, 56, 61, 79, 97],
 'Exam 3': [80, 111, 67, 67, 83, 101]}

I have figured out how to do below, but I need it to iterate over the assignments and not be hard coded and I can't figure out how- I have a separate function called get_assignments() that I can pull the assignments into a list: ['Exam 1', 'Exam 2', 'Exam 3'].

Here is my solution but how do I loop through assignments and make them the keys?

def build_grade_by_asn(grades):
    grades_by_asn = {'Exam 1': [], 'Exam 2': [], 'Exam 3': []}
    for row in grades[1:]:
        grades_by_asn['Exam 1'].append(int(row[1]))
        grades_by_asn['Exam 2'].append(int(row[2]))
        grades_by_asn['Exam 3'].append(int(row[3]))
    return dict(grades_by_asn)

CodePudding user response:

Try:

out = {k: list(map(int, v)) for k, *v in list(zip(*grades))[1:]}
print(out)

Prints:

{
    "Exam 1": [100, 88, 45, 59, 73, 89],
    "Exam 2": [90, 99, 56, 61, 79, 97],
    "Exam 3": [80, 111, 67, 67, 83, 101],
}

CodePudding user response:

You can just modify your solution like that:

def build_grade_by_asn(grades):
    grades_by_asn = {}
    for row in grades[1:]:
        for index, exam in enumerate(grades[0][1:], start=1):
            grades_by_asn.setdefault(exam, []).append(int(row[index]))
    return dict(grades_by_asn)

CodePudding user response:

A dictionary comprehension can group your data more usefully.

{colname: [line[i] for line in grades[1:]] for i, colname in enumerate(grades[0])}

Result:

{'Student': ['Thorny', 'Mac', 'Farva', 'Rabbit', 'Ursula', 'Foster'], 
 'Exam 1': ['100', '88', '45', '59', '73', '89'], 
 'Exam 2': ['90', '99', '56', '61', '79', '97'], 
 'Exam 3': ['80', '111', '67', '67', '83', '101']}

Now, if we use a conditional clause in the dictionary comprehension we can get rid of the 'Student' key.

{colname: [line[i] for line in grades[1:]] 
 for i, colname in enumerate(grades[0])
 if colname != 'Student'}

Result:

{'Exam 1': ['100', '88', '45', '59', '73', '89'], 
 'Exam 2': ['90', '99', '56', '61', '79', '97'], 
 'Exam 3': ['80', '111', '67', '67', '83', '101']}

And since you want the grades as ints...

{colname: [int(line[i]) for line in grades[1:]] 
 for i, colname in enumerate(grades[0])
 if colname != 'Student'}
  • Related