2

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?

Romano Vacca
  • 305
  • 1
  • 4
  • 11
  • 3
    Dictionaries are unordered by definition in Python. If you want to keep order, use `OrderedDict`. – Maroun Jul 12 '15 at 12:52
  • 1
    As an alternative you can use the `OrderedDict`: https://docs.python.org/2/library/collections.html#collections.OrderedDict – Klaus D. Jul 12 '15 at 12:53
  • 1
    A plain dictionary is very fast to access & efficient in memory use, but that power comes at a price. BTW, your `for` loop is a bit odd. You don't need `count`, you can just do `for element in res:` `print element` – PM 2Ring Jul 12 '15 at 13:51

2 Answers2

1

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.

Himanshu Mishra
  • 8,510
  • 12
  • 37
  • 74
0

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.

Mihai Hangiu
  • 588
  • 4
  • 13
  • 2
    I recommend against manually maintaining a list of keys, as this requires unnecessary administration that is done for you in OrderedDict. That's what it's for. – Joost Jul 12 '15 at 13:01
  • The order seems random because a `dict` is implemented as a [hash table](http://stackoverflow.com/questions/327311/how-are-pythons-built-in-dictionaries-implemented). – PM 2Ring Jul 12 '15 at 14:01