python - Should dict store key in order by inc? -


i have dict integers keys. tell me please, dict store data sorted keys or not?

i wrote little code test (as follows):

>>>  >>> d = {1: 'a', 3: 'a'} >>> d {1: 'a', 3: 'a'} >>> d[2] = 'a' >>> d {1: 'a', 2: 'a', 3: 'a'} >>>  

but not sure behavior standard , works time.

dictionaries in python not sorted. read more on dicts here: http://docs.python.org/library/stdtypes.html?highlight=dict#dict

but can use sorted python built-in method sort keys:

for k in sorted(mydict):     mydict[k] # 

or here collections.ordereddict implementation

you can mix sorted method , ordereddict use later(sure word in case not add new items - otherwise better use sorted method):

d = {1: 'a', 3: 'a'}    collections import ordereddict    sorted_d = ordereddict((k, d[k]) k in sorted(d)) 

Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -