subjects = ['Chem', 'Phy', 'Math']
students = ['Joy', 'Agatha', 'Mary', 'Frank', 'Godwin', 'Chizulum', 'Enoc', 'Chinedu', 'Kenneth', 'Lukas']
math = [76,56,78,98,88,75,59,80,45,30]
phy = [72,86,70,98,89,79,69,50,85,80]
chem = [75,66,77,45,83,75,59,40,65,90]
How do I transform the lists above to the nested dictionary below using pyhon
{
'math':{'joy':76, 'Agatha':56, 'Mary':78.....},
'phy':{'joy':72, 'Agatha':86, 'Mary':70....},
'chem':{'joy':75, 'Agatha':66, 'Mary':77....}
}
CodePudding user response:
This is certainly not the most elegant way to do this, but it works:
dictionary = {}
dict_math = {}
dict_phy = {}
dict_chem = {}
for i in range(len(students)):
dict_math[students[i]] = math[i]
dict_phy[students[i]] = phy[i]
dict_chem[students[i]] = chem[i]
dictionary['math'] = dict_math
dictionary['phy'] = dict_phy
dictionary['chem'] = dict_chem
print(dictionary)
CodePudding user response:
With the given lists, you could build the result dictionary this way :
result_dict = {
subject: {
name: grade for name in students for grade in globals()[subject.lower()]
}
for subject in subjects
}
This solution uses a nested dictionary comprehension and isn't meant for beginners. On top of that the use of built-in globals()
is not recommanded and only suits in this particular case.
CodePudding user response:
You can do something like that:
math_grades = list(zip(students, math))
phy_grades = list(zip(students, phy))
chem_grades = list(zip(students, chem))
your_dict = {
"math": {c: d for c, d in math_grades},
"phy": {c: d for c, d in phy_grades},
"chem": {c: d for c, d in chem_grades},
}