1

I'm a newbie to Python.

Here I have defined a dictionary:

dic = {"hello":"is_done", "bye":'is_gone', "things":'thinking'};

And then I have looped through it for it to return the data as expected:

for item in dic : 
 print("this is an item from our dictionary: "+dic[item]);

Here is the output:

this is an item from our dictionary: is_gone
this is an item from our dictionary: thinking
this is an item from our dictionary: is_done

Why is the order of iteration for producing output different from the order in which the key:value pairs were initialized in the dictionary object?

treddy
  • 2,771
  • 2
  • 18
  • 31
  • Agree on duplicate, but that answer could be improved :). Remember keys in a dictionary are a set, not a list. – Derek Litz Dec 19 '13 at 14:43
  • dictionaries are not ordered in any obvious way, that's why the values are printing out of order to what you expected. Check the link Eric provided for more info. – Totem Dec 19 '13 at 14:44
  • thanks I got it now. very much thanks –  Dec 19 '13 at 14:47

1 Answers1

1

As some comments have already pointed out: builtin dicts in python are unordered, one cannto make assumptions about the order in which stuff comes out on iterating. If you need an order, use Ordered Dicts.

Keeping the dict in order involves an additional cost on insert, and ít is normally not needed to have it in order for most applications. That is why the basic one does not care about it.

jcklie
  • 4,054
  • 3
  • 24
  • 42