簡體   English   中英

如何使用 python 將這些多個列表轉換成一個大字典

[英]How do I convert these multiple lists into a big dictionary using python

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]

如何使用 pyhon 將上面的列表轉換為下面的嵌套字典

{
'math':{'joy':76, 'Agatha':56, 'Mary':78.....},
'phy':{'joy':72, 'Agatha':86, 'Mary':70....},
'chem':{'joy':75, 'Agatha':66, 'Mary':77....}
}

使用給定的列表,您可以這樣構建結果字典:

result_dict = {
    subject: {
        name: grade for name in students for grade in globals()[subject.lower()]
    }
    for subject in subjects
}

此解決方案使用嵌套字典理解,並不適合初學者。 除此之外,不推薦使用內置globals() ,僅適用於這種特殊情況。

這當然不是最優雅的方式,但它確實有效:

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)

你可以這樣做:

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

你可以這樣做:

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]

grades = {
      "math": dict(zip(students, math)),
      "phy": dict(zip(students, phy)),
      "chem": dict(zip(students, chem)),
}

暫無
暫無

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

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