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?
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}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With