how reliable is python’s dictionary ordering? -


i need hash dictionary (a counter), , i’m noticing python seems order dictionaries same keys in same order, if constructed differently. in fact dictionaries seem able survive quite bit of abuse:

>>> d = {'a': 1, 'b': 2, 'c': 3} >>> list(d) ['b', 'c', 'a'] >>> list(d) ['b', 'c', 'a'] >>> list(d) ['b', 'c', 'a'] >>> list(d) ['b', 'c', 'a'] >>> e = {'a': 1, 'b': 2, 'c': 3} >>> list(e) ['b', 'c', 'a'] >>> list(e) ['b', 'c', 'a'] >>> list(e) ['b', 'c', 'a'] >>> f = {'a': 1, 'b': 2, 'c': 3} >>> list(f) ['b', 'c', 'a'] >>> list(f) ['b', 'c', 'a'] >>> list(f) ['b', 'c', 'a'] >>> list(f) ['b', 'c', 'a'] >>> g = {'a': 1, 'b': 2, 'c': 3, 'd': 4} >>> list(g) ['b', 'c', 'a', 'd'] >>> list(g) ['b', 'c', 'a', 'd'] >>> list(g) ['b', 'c', 'a', 'd'] >>> list(f) ['b', 'c', 'a'] >>> f.pop('a') 1 >>> list(f) ['b', 'c'] >>> f['a'] = 2 >>> list(f) ['b', 'c', 'a'] >>> list(f) ['b', 'c', 'a'] >>> h = {'b': 2, 'a': 1, 'c': 3} >>> list(h) ['b', 'c', 'a'] >>> h = {'b': 2, 'c': 1, 'a': 3} >>> list(h) ['b', 'c', 'a'] >>> k = {'b': 2, 'c': 1, 'a': 3, 'd': 4} >>> list(k) ['b', 'c', 'a', 'd'] >>> k = {'b': 2, 'c': 1, 'd': 3, 'a': 4} >>> list(k) ['b', 'c', 'a', 'd'] 

my question then, if dictionaries have same keys , same values, can count on keys being in same order, @ least lifetime of running instance of python? note i’m aware python bit incomprehensible in how decides order dictionary, want know if given same inputs, same instance of python return same key ordering each time.

in terms of language definition, no cannot rely on stable ordering, because not promised in language definition.

now, might on short- , medium-term find ordering stable, , makes sense: computers deterministic, it's reasonable expect same results 1 iteration of experiment next. (however, since complex systems, nondeterministic machine might still produce unexpected results, since don't know factors determinant) however, reasoning not extend long-term, should programming to, because language implementation free choose means of ordering keys likes, , change choice @ time, long implementation consistent language definition. means programs depending on order remaining stable subject breakage if run under different implementations, , subject breakage when implementation updated. not place want be, therefore should not make assumptions stability of ordering of dictionary keys.

that being said, if only concerned stability just across lifetime of 1 running instance of python seems safe gamble - again, computers deterministic - still gamble. test against cases rather more complex ones you're expecting encounter, , decide whether chopping block looks comfortable place rest neck.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -