Student Becomes the Teacher [Lesson Number One] - unexpected output


#1

I found the solution and had the program print the dictionaries at the end, the output surprised me a bit was wondering why it rearranged the key’s and values from what was entered?

The expected print for this would be:

{key 0 : value 0 , key 1 : value 1, key 2 : value 2, key 3 : value 3}

instead I seem to be getting
{key 2 : value 2 , key 3 : value 3, key 0 : value 0, key 1 : value 1}

Anyone able to explain what is going on with it? or is it doing what it is supposed to?


#2

Dictionaries do not remember the order that data is inserted. That means the output order cannot be predicted.


#3

Okay, good to know. Thanks.


Dictionary outputs are chaotic
#4

We’ve just been informed that Python 3.7 does remember insertion order, but this is Python 2.7.


#5

That’s also good to keep in mind, didn’t think of that. Thanks Roy!


#6
>>> lloyd = {
  'name': 'Lloyd',
  'homework': [],
  'quizzes': [],
  'tests': [],
}
>>> alice = {
  'name': 'Alice',
  'homework': [],
  'quizzes': [],
  'tests': [],
}
>>> tyler = {
  'name': 'Tyler',
  'homework': [],
  'quizzes': [],
  'tests': [],
}
>>> students = [alice, lloyd, tyler]
>>> fixed = ['homework', 'quizzes', 'tests']
>>> for student in students:
    print (student['name'])
    for j in fixed:
        print(j, student[j])
Alice
homework []
quizzes []
tests []
Lloyd
homework []
quizzes []
tests []
Tyler
homework []
quizzes []
tests []
>>> 

#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.