Should dict store key in order by inc?
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:
for k in sorted(myDict):
myDict[k] # do something
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):
d = {1: 'a', 3: 'a'}
from collections import OrderedDict
sorted_d = OrderedDict((k, d[k]) for k in sorted(d))
A little bit more experimenting would have soon shown you that they are not sorted:
>>> d = {1: 'a', 3: 'a', 8: 'a'}
>>> d
{8: 'a', 1: 'a', 3: 'a'}
but even that is implementation dependant. Don't depend on the order at all.
The internal dict keeps no sorting order for the keys. If you want a fast C-implementation for C python have a look at sorteddict which is included in my ordereddict package for CPython: http://anthon.home.xs4all.nl/Python/ordereddict/
精彩评论