I have a dict with integers as keys. Tell me please, does a dict store data with sorted keys or not?
I wrote a little code to test (as follows):
>>>
>>> d = {1: 'a', 3: 'a'}
>>> d
{1: 'a', 3: 'a'}
>>> d[2] = 'a'
>>> d
{1: 'a', 2: 'a', 3: 'a'}
>>>
But I am not sure that this behavior is standard and works all the time.
Dictionaries in python are not sorted. Read more on dicts here:
http://docs.python.org/library/stdtypes.html?highlight=dict#dict
But you can use sorted python built-in method to sort keys:
Or Look here for collections.OrderedDict implementation
You can also mix sorted method and OrderedDict to use it later(sure this will only word in case you will not add new items into it – otherwise it simply better to use sorted method):