Why is the order of dict and dict.items() different?
<pre><code>&gt;&gt;&gt; d = {'A':1, 'b':2, 'c':3, 'D':4}

&gt;&gt;&gt; d
{'A': 1, 'D': 4, 'b': 2, 'c': 3}

&gt;&gt;&gt; d.items()
[('A', 1), ('c', 3), ('b', 2), ('D', 4)]
</code></pre>

<p>Does the order get randomized twice when I call d.items()? Or does it just get randomized differently? Is there any alternate way to make d.items() return the same order as d? </p>

<p>Edit: Seems to be an IPython thing where it auto sorts the dict. Normally dict and dict.items() should be in the same order.</p>

<p>You seem to have tested this on IPython. IPython uses its own specialized pretty-printing facilities for various types, and the pretty-printer for dicts sorts the keys before printing (if possible). The <code>d.items()</code> call doesn't sort the keys, so the output is different.</p>

<p>In an ordinary Python session, the order of the items in the dict's <code>repr</code> would match the order of the items from the <code>items</code> method. Dict iteration order is supposed to be stable as long as a dict isn't modified. (This guarantee is not explicitly extended to the dict's <code>repr</code>, but it would be surprising if the implicit iteration in <code>repr</code> broke consistency with other forms of dict iteration.)</p>

python python-2.7 dictionary ipython