Context of the question
This is more a curiosity about how the Python interpreter works than a real issue (though I hope it is an acceptable question anyway).
In my specific case (maybe it doesn't matter, I don't know) I'm running the 3.5 intepreter (32 bit) on windows 7 (64 bit).
Running code
This is the simple code that I'm running from the Python 3.5 interpreter.
counter_example = {}
counter_example['one'] = 1
counter_example['two'] = 2
counter_example['three'] = 3
for currkey, currvalue in counter_example.items():
print ('%s - %s' % (currkey, currvalue))
I start an interpreter windows A and I run this code more times (let's say 3-4 times), then I start a second python interpreter window and again I run the code 3-4 times and finally the same thing with a third intepreter window C.
The output
I've noticed that - if I execute this more times on the same interpreter window, I get always the same output, meaning in the same order.
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> counter_example = {}
>>> counter_example['one'] = 1
>>> counter_example['two'] = 2
>>> counter_example['three'] = 3
>>> for currkey, currvalue in counter_example.items():
... print ('%s - %s' % (currkey, currvalue))
...
two - 2
one - 1
three - 3
>>> counter_example = {}
>>> counter_example['one'] = 1
>>> counter_example['two'] = 2
>>> counter_example['three'] = 3
>>> for currkey, currvalue in counter_example.items():
... print ('%s - %s' % (currkey, currvalue))
...
two - 2
one - 1
three - 3
>>>
On a different command-window the output will be in a different order but - surprisingly IMHO - the order of the items will be kept if I rerun the test there, starting again from the dictionary declaration. Why does this happen? What is happening behind the scenes?
Please note
I'm aware that I can do either this
for currkey, currvalue in sorted(counter_example.items()):
or that
from collections import OrderedDict
counter_example = OrderedDict()
But that's not what I'm asking for.