2013-07-19 33 views
0

我想學習與codeacademy python。 這項任務是製作3本字典(每個學生),然後列出3本字典。那麼,我應該打印列表中的所有數據。如何從字典列表中調用字典值?

我試圖用自己的字典(lloyd [values])用同樣的方式調出這些值,但之後它表示值沒有被定義爲o_O。我也嘗試'打印姓名',但是錯誤信息是我沒有打印出其中的一個值。

非常感謝您的幫助。

lloyd = { 
    "name": "Lloyd", 
    "homework": [90.0, 97.0, 75.0, 92.0], 
    "quizzes": [88.0, 40.0, 94.0], 
    "tests": [75.0, 90.0] 
} 
alice = { 
    "name": "Alice", 
    "homework": [100.0, 92.0, 98.0, 100.0], 
    "quizzes": [82.0, 83.0, 91.0], 
    "tests": [89.0, 97.0] 
} 
tyler = { 
    "name": "Tyler", 
    "homework": [0.0, 87.0, 75.0, 22.0], 
    "quizzes": [0.0, 75.0, 78.0], 
    "tests": [100.0, 100.0] 
} 
students = [lloyd, alice, tyler] 
for names in students: 
    print lloyd[values] 
+2

'values' is not defined;它不是你可以傳遞給'lloyd [']'的變量。你的意思是'names.values()'而不是? –

回答

3

如果你想打印爲每一個學生的所有信息,你必須遍歷所有的學生和值存儲在詞典:

students = [lloyd, alice, tyler] 
for student in students: 
    for value in student: 
     print value, "is", student[value] 

但是,請注意,字典沒有排序,所以值的順序可能不是您想要的方式。在這種情況下,單獨打印出來,使用值的名字作爲一個字符串鍵:

for student in students: 
    print "Name is", student["name"] 
    print "Homework is", student["homework"] 
    # same for 'quizzes' and 'tests' 

最後,您還可以使用pprint模塊「漂亮打印」學生字典:

import pprint 
for student in students: 
    pprint.pprint(student) 
+0

+1對於pprint很有用 –

0

所以students是詞典的列表。然後你要

for student in students: 
    print student['name'] 

而且當你要調用你必須把鑰匙在引號字典的關鍵,作爲一個字符串:alice[homework]不起作用因爲Python認爲homework是一個變量。您需要改爲alice['homework']

所以要考慮所有的信息很好,你可以做

for student in students: 
    for field in student.keys(): 
     print "{}: {}".format(field, student[field]) 

可以隨意修改,使格式更好,例如打印的名頭,將每個新學生之間的新線等

+0

我不認爲這就是他要問的。 –

2

你可以簡單地打印值的類型的字典:

for names in students: 
    print names #names are the dictionaries 

如果你想打印只是名字,然後用name關鍵:

for student in students: 
    print student['name'] 
2

我會建議使用namedtuple代替了可讀性和可擴展性:

from collections import namedtuple 

Student = namedtuple('Student', ['name', 'hw', 'quiz', 'test']) 

Alice = Student('Alice', herHWLst, herQuizLst, herTestLst) 
Ben = Student('Ben', hisHWLst, hisQuizLst, hisTestLst) 

students = [Alice, Ben] 

for student in students: 
    print student.name, student.hw[0], student.quiz[1], student.test[2] 
    #whatever value you want 

如果你真的想創建噸字典,你可以讀它的機智^ h代碼上面的:

for student in students: 
    name = student['name'] 
    homeworkLst = student['homework'] 
    # get more values from dict if you want 
    print name, homeworkLst 

訪問字典是Python中的超級快,但他們創造可能不會像快速和有效的。在這種情況下,命名元組更實用。

0

這就是我在codeacademy上解決我的問題。希望有人認爲學生在學生這是很有幫助的 :

print student['name'] 
print student['homework'] 
print student['quizzes'] 
print student['tests'] 
0

這是我讓他們接受。

for name in students: 
    print name["name"] 
    print name["homework"] 
    print name["quizzes"] 
    print name["tests"] 

這也行得通,但他們不會接受。

for name in students: 
    print name