[英]Iterating over a list and using a dictionary to extract the value
我已經嘗試解決這個問題好幾個小時了,希望能得到一些幫助:所以我有一個列表和一個字典可以使用:
new_list = ['A', 'B', 'E', 'G', 'H', 'I', 'J', 'K', 'L', 'N', 'O', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Z']
grades_per_student = {'A': 80, 'B': 80, 'C': 84, 'D': 96, 'E': 75, 'F': 83, 'G': 74, 'H': 79, 'I': 60, 'J': 70, 'K': 68, 'L': 55, 'M': 88, 'N': 77, 'O': 80, 'P': 81, 'Q': 79, 'R': 60, 'S': 57, 'T': 72, 'U': 56, 'V': 77, 'W': 75, 'X': 75, 'Y': 97, 'Z': 73}
我的工作是遍歷new_list
變量並使用字典鍵和值打印出字符串及其對應的 integer。
這是我嘗試過的:
for key,value in grades_per_student.items():
new_list.append(value)
print(new_list)
當我運行代碼時,這就是我得到的:
['A', 'B', 'E', 'G', 'H', 'I', 'J', 'K', 'L', 'N', 'O', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Z', 80, 80, 84, 96, 75, 83, 74, 79, 60, 70, 68, 55, 88, 77, 80, 81, 79, 60, 57, 72, 56, 77, 75, 75, 97, 73]
它足夠接近,但我試圖得到這樣的東西: ['A':80, 'B':80, 'E':75, etc...]
。 當我應該迭代列表時,我也認為我正在迭代字典。
您正在迭代grades_per_student
但您應該迭代new_list
:
for i in new_list:
print(f'{i}: {grades_per_student[i]}')
您只是使用new_list.append(value)
將值附加到列表的末尾。 為什么要列表? 你不能只使用字典嗎?
如果你真的想要一個列表,我會做這樣的事情:
new_list = []
for key, value in grades_per_student.items():
pair = str(key) + ":" + str(value)
new_list.append(pair)
print(new_list)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.