Reputation: 4778
I executed this snippet:
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 i in students:
for f in i:
print i[f]
I don't understand why output is the next:
[88.0, 40.0, 94.0]
[75.0, 90.0]
Lloyd
[90.0, 97.0, 75.0, 92.0]
[82.0, 83.0, 91.0]
[89.0, 97.0]
Alice
[100.0, 92.0, 98.0, 100.0]
[0.0, 75.0, 78.0]
[100.0, 100.0]
Tyler
[0.0, 87.0, 75.0, 22.0]
Why it happens so? Where I can find docs for that? Could someone give me short explanation for logic of output?
Upvotes: 1
Views: 1341
Reputation: 97601
You can easily fix this with a changed loop:
for student in students:
for key in ["name", "homework", "quizzes", "tests"]:
print student[key]
Namedtuples might be a better match here:
from collections import namedtuple
Student = namedtuple('Student', ["name", "homework", "quizzes", "tests"])
students = [
Student(name="Lloyd",
homework=[90.0, 97.0, 75.0, 92.0],
quizzes=[ 88.0, 40.0, 94.0],
tests=[75.0, 90.0])
Student(name="Alice",
homework=[100.0, 92.0, 98.0, 100.0],
quizzes=[82.0, 83.0, 91.0],
tests=[89.0, 97.0])
Student(name="Tyler",
homework=[0.0, 87.0, 75.0, 22.0],
quizzes=[0.0, 75.0, 78.0],
tests=[100.0, 100.0])
]
Upvotes: 2
Reputation: 435
Regular dictionaries are not ordered.
It is best to think of a dictionary as an unordered set of key: value pairs
If you really need an ordered dictionary, look into OrderedDict.
Upvotes: 6
Reputation: 185892
Dictionary keys don't have a defined ordering. {'a':1,'b':2}
and {'b':2,'a':1}
are considered equal, and they print out the same way:
>>> {'a':1, 'b':2}
{'a': 1, 'b': 2}
>>> {'b':2, 'a':1}
{'a': 1, 'b': 2}
Note, also, from your own experience, that you can't assume they'll come out in alphabetical order.
Upvotes: 6