Do string representations of dictionaries have order in Python 3.4?

2024/7/5 11:12:19

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?

Answer

Note: Python 3.6 introduces a new, order-preserving implementation of dict, which makes the following obsolete from 3.6 onwards.


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 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:

By default, the __hash__() values of str, bytes and datetime objects are “salted” with an unpredictable random value. Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python.

This is intended to provide protection against a denial-of-service caused by carefully-chosen inputs that exploit the worst case performance of a dict insertion, O(n^2) complexity. See http://www.ocert.org/advisories/ocert-2011-003.html for details.

Changing hash values affects the iteration order of dicts, sets and other mappings. Python has never made guarantees about this ordering (and it typically varies between 32-bit and 64-bit builds).

https://en.xdnf.cn/q/120089.html

Related Q&A

BeautifulSoup Scraping Results not showing

I am playing around with BeautifulSoup to scrape data from websites. So I decided to scrape empireonlines website for 100 greatest movies of all time. Heres the link to the webpage: https://www.empireo…

How to verify username and password from CSV file in Python?

I am doing a Python project where I have to verify my username and password from a csv file where the first two rows and columns have the username and password as hi.Current Code: answer = input("…

adding validation to answer in quiz gives wrong answers

I am a complete novice with Python and working on a multiple choice quiz that reads questions from a file and keeps a score that then writes to a file. Everything was working perfectly until I added v…

Why do I get None as the output from a print statement? [duplicate]

This question already has answers here:Why is "None" printed after my functions output?(7 answers)Closed 2 years ago.def print_name(name):print(name)print(print_name(Annabel Lee))Why do I ge…

How to collect tweets about an event that are posted on specific date using python?

I wish to collect all tweets containing specific keywords(ex:manchesterattack,manchester) that are posted about the manchester attack from 22may. Can anyone provide me a code to collect tweets using py…

Pivoting a One-Hot-Encode Dataframe

I have a pandas dataframe that looks like this:genres.head()Drama Comedy Action Crime Romance Thriller Adventure Horror Mystery Fantasy ... History Music War Documentary Sport Musical W…

How to declare multiple similar variables in python? [duplicate]

This question already has answers here:How do I create variable variables?(18 answers)Closed 5 years ago.How can I declare multiple (about 50) variables that count from slider1 to slider50 ? Is there…

what does means this error broken pipe? [duplicate]

This question already has answers here:Closed 11 years ago.Possible Duplicate:TCP client-server SIGPIPE I would like know what does this error mean?

Apply a function to each element of a pandas series

I am trying to tokenize each sentence of my pandas series. I try to do as I see in the documentation, using apply, but didnt work:x.apply(nltk.word_tokenize)If I just use nltk.word_tokenize(x) didnt wo…

ValueError: could not convert string to float: in Python 3.10

When someone writes a string or a letter, I want the code make them go back, and the code to print "must be a number and bigger than 0 and less than 100", but what actually happens is the cod…