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?

3
  • 3
    Dictionaries are unordered by definition in Python. If you want to keep order, use OrderedDict. Commented Jul 12, 2015 at 12:52
  • 1
    As an alternative you can use the OrderedDict: docs.python.org/2/library/… Commented Jul 12, 2015 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 Commented Jul 12, 2015 at 13:51

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Well if he wants 104, 105, 106 then he can just sort the values numerically too.
The question feels more about why to the dictionary behavior than how to get a sorted output..
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.

2 Comments

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.
The order seems random because a dict is implemented as a hash table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.