I know dictionaries themselves in Python do not have order. However, I'm rather curious if when you call str()
on a dictionary if it is always in the same order. It appears to be sorted (by key), no matter which order I add items:
d={}
d[5]=5
d[1]=1
d["z"]="z"
d["a"]="a"
s=str(d)
print(s)
I know a lot of people will be tempted to say it's not sorted, but please try to prove me wrong by getting unsorted results.
So, are dictionaries converted to strings sorted, by default, in Python 3.4?
Here are three iterations of your example in three different Python 3.4 interpreter sessions:
So, no, the string representation is not sorted, or even in the same order across invocations of the interpreter. In versions of Python up to and including 3.2, the order of dictionaries (and their string representations) was arbitrary but consistent - however, this changed in Python 3.3 as a result of a security fix:
No, they are not.
output (will change every time you run because of hash randomization):