Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is the python dict str() function reliably sorting keys?

in python, both the dict {1:1,2:2,3:3} and {3:3,2:2,1:1} produces "{1:1,2:2,3:3}" when str()'d?

Can I rely on this sorting, or at least on the fact that dicts containing the same key/valuepairs will generate the same string when put through the str() function?

like image 805
bigblind Avatar asked Nov 27 '11 21:11

bigblind


2 Answers

You can rely on neither of these two properties. The order of a dictionary when converted to a string depends also on the insertion order of the key/value pairs.

With a bit of knowledge of the Python source code (watch The Mighty Dictionary from PyCon 2010), or a bit of trial and error, you can easily find counter examples:

>>> {1: 1, 9: 9}
{1: 1, 9: 9}
>>> {9: 9, 1: 1}
{9: 9, 1: 1}
like image 136
Sven Marnach Avatar answered Sep 21 '22 02:09

Sven Marnach


The dict built-in type does not guarantee any particular order of the keys.

Even if it seems that you always get the same string, don't rely on this. If you do, when you upgrade Python there might be a change in the implementation which causes your assumption to fail.

The OrderedDict class does provide guarantees about the order of the keys.

like image 42
Mark Byers Avatar answered Sep 23 '22 02:09

Mark Byers