簡體   English   中英

如何使用zip將不相等的列表轉換為python中的嵌套字典

[英]how to convert unequal list to nested dictionary in python using zip

請問如何將此列表轉換為嵌套字典?

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]

得到這個輸出

{
    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},
}

您可以嵌套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}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM