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
Post a Comment