我在嵌套字典中分配困難。我有一個嵌套的詞典,有兩個學校,三個老師和四個學生。這僅僅是一個玩具的例子,所以我不在乎每個學校的學生和老師都是一樣的。但是,我希望每個等級都不同。但是,根據下面的代碼,所有班級和所有學校的所有學生的成績與最後輸入的學校/班級相同。嵌套字典分配錯誤 - 混淆可變字典
schools = ['School A', 'School B']
teachers = ['mr. smith', 'ms. jones', 'mr. kronk']
students = ['Adam', 'Nick', 'Jeff', 'Dave']
grade_dict ={}
for i in students:
grade_dict[i] = ''
for j in teachers:
teachers_dict[j] = grade_dict
for k in schools:
school_dict[k] = teachers_dict
for k in schools:
for j in teachers:
for i in students:
a = [randint(70, 100), randint(70, 100), randint(70, 100)]
school_dict[k][j][i] = a
這就是我想要的數據看起來像:
School A mr. smith Adam [71, 72, 82]
School A mr. smith Nick [86, 80, 96]
School A mr. smith Jeff [77, 70, 83]
School A mr. smith Dave [79, 83, 98]
School A ms. jones Adam [70, 98, 87]
School A ms. jones Nick [80, 94, 76]
School A ms. jones Jeff [79, 82, 93]
School A ms. jones Dave [90, 97, 85]
School A mr. kronk Adam [93, 75, 95]
School A mr. kronk Nick [80, 82, 72]
School A mr. kronk Jeff [75, 72, 89]
School A mr. kronk Dave [86, 92, 98]
School B mr. smith Adam [89, 77, 84]
School B mr. smith Nick [93, 71, 74]
School B mr. smith Jeff [78, 83, 83]
School B mr. smith Dave [72, 83, 70]
School B ms. jones Adam [82, 100, 78]
School B ms. jones Nick [80, 89, 100]
School B ms. jones Jeff [91, 81, 77]
School B ms. jones Dave [86, 86, 74]
School B mr. kronk Adam [82, 73, 100]
School B mr. kronk Nick [81, 71, 74]
School B mr. kronk Jeff [92, 100, 90]
School B mr. kronk Dave [86, 97, 85]
這不幸的是,相應的字典的樣子:
{'School A': {'mr. kronk': {'Adam': [86, 89, 94],
'Dave': [74, 85, 86],
'Jeff': [79, 94, 70],
'Nick': [90, 80, 97]},
'mr. smith': {'Adam': [86, 89, 94],
'Dave': [74, 85, 86],
'Jeff': [79, 94, 70],
'Nick': [90, 80, 97]},
'ms. jones': {'Adam': [86, 89, 94],
'Dave': [74, 85, 86],
'Jeff': [79, 94, 70],
'Nick': [90, 80, 97]}},
'School B': {'mr. kronk': {'Adam': [86, 89, 94],
'Dave': [74, 85, 86],
'Jeff': [79, 94, 70],
'Nick': [90, 80, 97]},
'mr. smith': {'Adam': [86, 89, 94],
'Dave': [74, 85, 86],
'Jeff': [79, 94, 70],
'Nick': [90, 80, 97]},
'ms. jones': {'Adam': [86, 89, 94],
'Dave': [74, 85, 86],
'Jeff': [79, 94, 70],
'Nick': [90, 80, 97]}}}
似乎有類似的問題在stackoverflow,但他們不能幫助我解決這裏發生的事情。謝謝。
硬編碼像這樣最終的字典是不是最好的。 –
這是初始化字典的一種很酷的方式(謝謝!),但並不完全解決在嵌套字典中最低級別創建唯一值的問題。 –
@GeoffPerrin我很抱歉沒有意識到你想讓學生成績隨機化!請參閱我最近的編輯。 – Ajax1234