How to convert unequal list to nested dictionary using zip?
Question:
How can I convert this list to nested dictionary?
studentName = ["kelly","Micheal","Agatha","Chris","frank","matthew"]
subject = ["math","phy","chem"]
math = [34,45,78,79,60,36]
phy = [57,98,67,90,56,60]
chem = [67,86,35,98,50,67]
To get this output:
{
kelly:{math:34,phy:57,chem:67},
micheal:{math:45,phy:98,chem:86},
Agatha:{math:78,phy:67,chem:35},
chris:{math:79,phy:90,chem:98},
frank:{math:60,phy:56,chem:50},
matthew: {math:36,phy:60,chem:67},
}
Answers:
You can nest zip
s:
studentName = ["kelly","Micheal","Agatha","Chris","frank","matthew"]
subject = ["math","phy","chem"]
math = [34,45,78,79,60,36]
phy = [57,98,67,90,56,60]
chem = [67,86,35,98,50,67]
output = {name: dict(zip(subject, scores)) for name, scores in
zip(studentName, zip(math, phy, chem))}
print(output)
# {'kelly': {'math': 34, 'phy': 57, 'chem': 67},
# 'Micheal': {'math': 45, 'phy': 98, 'chem': 86},
# 'Agatha': {'math': 78, 'phy': 67, 'chem': 35},
# 'Chris': {'math': 79, 'phy': 90, 'chem': 98},
# 'frank': {'math': 60, 'phy': 56, 'chem': 50},
# 'matthew': {'math': 36, 'phy': 60, 'chem': 67}}
How can I convert this list to nested dictionary?
studentName = ["kelly","Micheal","Agatha","Chris","frank","matthew"]
subject = ["math","phy","chem"]
math = [34,45,78,79,60,36]
phy = [57,98,67,90,56,60]
chem = [67,86,35,98,50,67]
To get this output:
{
kelly:{math:34,phy:57,chem:67},
micheal:{math:45,phy:98,chem:86},
Agatha:{math:78,phy:67,chem:35},
chris:{math:79,phy:90,chem:98},
frank:{math:60,phy:56,chem:50},
matthew: {math:36,phy:60,chem:67},
}
You can nest zip
s:
studentName = ["kelly","Micheal","Agatha","Chris","frank","matthew"]
subject = ["math","phy","chem"]
math = [34,45,78,79,60,36]
phy = [57,98,67,90,56,60]
chem = [67,86,35,98,50,67]
output = {name: dict(zip(subject, scores)) for name, scores in
zip(studentName, zip(math, phy, chem))}
print(output)
# {'kelly': {'math': 34, 'phy': 57, 'chem': 67},
# 'Micheal': {'math': 45, 'phy': 98, 'chem': 86},
# 'Agatha': {'math': 78, 'phy': 67, 'chem': 35},
# 'Chris': {'math': 79, 'phy': 90, 'chem': 98},
# 'frank': {'math': 60, 'phy': 56, 'chem': 50},
# 'matthew': {'math': 36, 'phy': 60, 'chem': 67}}