Note. Python 3.6 introduces a new implementation of preserving order in a dict , which does after obsolete ones with 3.6 and higher.
Here are three iterations of your example in three different Python 3.4 interpreter sessions:
Python 3.4.1 (default, Aug 8 2014, 15:05:42) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> d={} >>> d[5]=5 >>> d[1]=1 >>> d["z"]="z" >>> d["a"]="a" >>> s=str(d) >>> print(s) {1: 1, 'z': 'z', 'a': 'a', 5: 5}
Python 3.4.1 (default, Aug 8 2014, 15:05:42) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> d={} >>> d[5]=5 >>> d[1]=1 >>> d["z"]="z" >>> d["a"]="a" >>> s=str(d) >>> print(s) {1: 1, 'a': 'a', 5: 5, 'z': 'z'}
Python 3.4.1 (default, Aug 8 2014, 15:05:42) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> d={} >>> d[5]=5 >>> d[1]=1 >>> d["z"]="z" >>> d["a"]="a" >>> s=str(d) >>> print(s) {1: 1, 5: 5, 'z': 'z', 'a': 'a'}
So, no, the string representation is not sorted, or even in the same order through interpreter calls. In versions of Python up to and including 3.2, the order of dictionaries (and their string representations) was arbitrary but sequential - however, this changed in Python 3.3 as a result of security :
By default, the __hash__() values โโof str, bytes, and datetime are salty with an unpredictable random value. Although they remain constant within a separate Python process, they are not predictable between Python repeated calls.
This is intended to provide denial of service protection caused by carefully selected inputs that use the worst performance for inserting a dict, complexity O (n ^ 2). See http://www.ocert.org/advisories/ocert-2011-003.html for more details.
Changing hash values โโaffects the order of iterations of dicts, sets, and other mappings. Python never provided a guarantee about this order (and it usually varies between 32-bit and 64-bit builds).