Reputation: 315
I just started with the Python course from codecademy. I am trying to return the dic values in the order as they are in the dictionary.
residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}
res = residents.values()
count = 0
for element in res:
print res[count]
count += 1
The output I received: 105 104 106
From this I get that i do not fully understand how the for-loop or dictionary works, I was expecting to get 104 105 106 as output. Can someone explain this?
Upvotes: 2
Views: 111
Reputation: 9376
Dictionaries are not ordered in Python. Many a time I tried running loops over them and expected output in the same order as I gave it the input but it didn't work. So I guess, it's no fault of the for loop
.
As Maroun suggests in the comments, you should be using OrderedDict
for that.
Upvotes: 1
Reputation: 598
You cannot get the keys nor associated values from a dict in the order you put them there. The order you get them seems to be random.
If you want an ordered dict please use collections.OrderedDict or store the keys in a list an work with both: a list keeping the keys in the ordered they were added to dict and the actual dict.
Upvotes: 0