Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Actually pprint seems to sort the keys for you under python2.5</p> <pre><code>&gt;&gt;&gt; from pprint import pprint &gt;&gt;&gt; mydict = {'a':1, 'b':2, 'c':3} &gt;&gt;&gt; pprint(mydict) {'a': 1, 'b': 2, 'c': 3} &gt;&gt;&gt; mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5} &gt;&gt;&gt; pprint(mydict) {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} &gt;&gt;&gt; d = dict(zip("kjihgfedcba",range(11))) &gt;&gt;&gt; pprint(d) {'a': 10, 'b': 9, 'c': 8, 'd': 7, 'e': 6, 'f': 5, 'g': 4, 'h': 3, 'i': 2, 'j': 1, 'k': 0} </code></pre> <p>But not always under python 2.4</p> <pre><code>&gt;&gt;&gt; from pprint import pprint &gt;&gt;&gt; mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5} &gt;&gt;&gt; pprint(mydict) {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} &gt;&gt;&gt; d = dict(zip("kjihgfedcba",range(11))) &gt;&gt;&gt; pprint(d) {'a': 10, 'b': 9, 'c': 8, 'd': 7, 'e': 6, 'f': 5, 'g': 4, 'h': 3, 'i': 2, 'j': 1, 'k': 0} &gt;&gt;&gt; </code></pre> <p>Reading the source code of pprint.py (2.5) it does sort the dictionary using</p> <pre><code>items = object.items() items.sort() </code></pre> <p>for multiline or this for single line</p> <pre><code>for k, v in sorted(object.items()): </code></pre> <p>before it attempts to print anything, so if your dictionary sorts properly like that then it should pprint properly. In 2.4 the second sorted() is missing (didn't exist then) so objects printed on a single line won't be sorted.</p> <p>So the answer appears to be use python2.5, though this doesn't quite explain your output in the question.</p> <p><strong>Python3 Update</strong></p> <p>Pretty print by sorted <em>keys</em> (lambda x: x[0]):</p> <pre><code>for key, value in sorted(dict_example.items(), key=lambda x: x[0]): print("{} : {}".format(key, value)) </code></pre> <p>Pretty print by sorted <em>values</em> (lambda x: x[1]):</p> <pre><code>for key, value in sorted(dict_example.items(), key=lambda x: x[1]): print("{} : {}".format(key, value)) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload