CINXE.COM

PEP 265 – Sorting Dictionaries by Value | peps.python.org

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="color-scheme" content="light dark"> <title>PEP 265 – Sorting Dictionaries by Value | peps.python.org</title> <link rel="shortcut icon" href="../_static/py.png"> <link rel="canonical" href="https://peps.python.org/pep-0265/"> <link rel="stylesheet" href="../_static/style.css" type="text/css"> <link rel="stylesheet" href="../_static/mq.css" type="text/css"> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" media="(prefers-color-scheme: light)" id="pyg-light"> <link rel="stylesheet" href="../_static/pygments_dark.css" type="text/css" media="(prefers-color-scheme: dark)" id="pyg-dark"> <link rel="alternate" type="application/rss+xml" title="Latest PEPs" href="https://peps.python.org/peps.rss"> <meta property="og:title" content='PEP 265 – Sorting Dictionaries by Value | peps.python.org'> <meta property="og:description" content="This PEP suggests a “sort by value” operation for dictionaries. The primary benefit would be in terms of “batteries included” support for a common Python idiom which, in its current form, is both difficult for beginners to understand and cumbersome for ..."> <meta property="og:type" content="website"> <meta property="og:url" content="https://peps.python.org/pep-0265/"> <meta property="og:site_name" content="Python Enhancement Proposals (PEPs)"> <meta property="og:image" content="https://peps.python.org/_static/og-image.png"> <meta property="og:image:alt" content="Python PEPs"> <meta property="og:image:width" content="200"> <meta property="og:image:height" content="200"> <meta name="description" content="This PEP suggests a “sort by value” operation for dictionaries. The primary benefit would be in terms of “batteries included” support for a common Python idiom which, in its current form, is both difficult for beginners to understand and cumbersome for ..."> <meta name="theme-color" content="#3776ab"> </head> <body> <svg xmlns="http://www.w3.org/2000/svg" style="display: none;"> <symbol id="svg-sun-half" viewBox="0 0 24 24" pointer-events="all"> <title>Following system colour scheme</title> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <circle cx="12" cy="12" r="9"></circle> <path d="M12 3v18m0-12l4.65-4.65M12 14.3l7.37-7.37M12 19.6l8.85-8.85"></path> </svg> </symbol> <symbol id="svg-moon" viewBox="0 0 24 24" pointer-events="all"> <title>Selected dark colour scheme</title> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> <path d="M12 3c.132 0 .263 0 .393 0a7.5 7.5 0 0 0 7.92 12.446a9 9 0 1 1 -8.313 -12.454z"></path> </svg> </symbol> <symbol id="svg-sun" viewBox="0 0 24 24" pointer-events="all"> <title>Selected light colour scheme</title> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <circle cx="12" cy="12" r="5"></circle> <line x1="12" y1="1" x2="12" y2="3"></line> <line x1="12" y1="21" x2="12" y2="23"></line> <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line> <line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line> <line x1="1" y1="12" x2="3" y2="12"></line> <line x1="21" y1="12" x2="23" y2="12"></line> <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line> <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line> </svg> </symbol> </svg> <script> document.documentElement.dataset.colour_scheme = localStorage.getItem("colour_scheme") || "auto" </script> <section id="pep-page-section"> <header> <h1>Python Enhancement Proposals</h1> <ul class="breadcrumbs"> <li><a href="https://www.python.org/" title="The Python Programming Language">Python</a> &raquo; </li> <li><a href="../pep-0000/">PEP Index</a> &raquo; </li> <li>PEP 265</li> </ul> <button id="colour-scheme-cycler" onClick="setColourScheme(nextColourScheme())"> <svg aria-hidden="true" class="colour-scheme-icon-when-auto"><use href="#svg-sun-half"></use></svg> <svg aria-hidden="true" class="colour-scheme-icon-when-dark"><use href="#svg-moon"></use></svg> <svg aria-hidden="true" class="colour-scheme-icon-when-light"><use href="#svg-sun"></use></svg> <span class="visually-hidden">Toggle light / dark / auto colour theme</span> </button> </header> <article> <section id="pep-content"> <h1 class="page-title">PEP 265 – Sorting Dictionaries by Value</h1> <dl class="rfc2822 field-list simple"> <dt class="field-odd">Author<span class="colon">:</span></dt> <dd class="field-odd">Grant Griffin &lt;g2&#32;&#97;t&#32;iowegian.com&gt;</dd> <dt class="field-even">Status<span class="colon">:</span></dt> <dd class="field-even"><abbr title="Formally declined and will not be accepted">Rejected</abbr></dd> <dt class="field-odd">Type<span class="colon">:</span></dt> <dd class="field-odd"><abbr title="Normative PEP with a new feature for Python, implementation change for CPython or interoperability standard for the ecosystem">Standards Track</abbr></dd> <dt class="field-even">Created<span class="colon">:</span></dt> <dd class="field-even">08-Aug-2001</dd> <dt class="field-odd">Python-Version<span class="colon">:</span></dt> <dd class="field-odd">2.2</dd> <dt class="field-even">Post-History<span class="colon">:</span></dt> <dd class="field-even"><p></p></dd> </dl> <hr class="docutils" /> <section id="contents"> <details><summary>Table of Contents</summary><ul class="simple"> <li><a class="reference internal" href="#abstract">Abstract</a></li> <li><a class="reference internal" href="#bdfl-pronouncement">BDFL Pronouncement</a></li> <li><a class="reference internal" href="#motivation">Motivation</a></li> <li><a class="reference internal" href="#rationale">Rationale</a></li> <li><a class="reference internal" href="#implementation">Implementation</a></li> <li><a class="reference internal" href="#concerns">Concerns</a></li> <li><a class="reference internal" href="#references">References</a></li> <li><a class="reference internal" href="#copyright">Copyright</a></li> </ul> </details></section> <section id="abstract"> <h2><a class="toc-backref" href="#abstract" role="doc-backlink">Abstract</a></h2> <p>This PEP suggests a “sort by value” operation for dictionaries. The primary benefit would be in terms of “batteries included” support for a common Python idiom which, in its current form, is both difficult for beginners to understand and cumbersome for all to implement.</p> </section> <section id="bdfl-pronouncement"> <h2><a class="toc-backref" href="#bdfl-pronouncement" role="doc-backlink">BDFL Pronouncement</a></h2> <p>This PEP is rejected because the need for it has been largely fulfilled by Py2.4’s <code class="docutils literal notranslate"><span class="pre">sorted()</span></code> builtin function:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">iteritems</span><span class="p">(),</span> <span class="n">key</span><span class="o">=</span><span class="n">itemgetter</span><span class="p">(</span><span class="mi">1</span><span class="p">),</span> <span class="n">reverse</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="go">[(&#39;b&#39;, 23), (&#39;d&#39;, 17), (&#39;c&#39;, 5), (&#39;a&#39;, 2), (&#39;e&#39;, 1)]</span> </pre></div> </div> <p>or for just the keys:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">sorted</span><span class="p">(</span><span class="n">d</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">d</span><span class="o">.</span><span class="fm">__getitem__</span><span class="p">,</span> <span class="n">reverse</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="p">[</span><span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;d&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">,</span> <span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;e&#39;</span><span class="p">]</span> </pre></div> </div> <p>Also, Python 2.5’s <code class="docutils literal notranslate"><span class="pre">heapq.nlargest()</span></code> function addresses the common use case of finding only a few of the highest valued items:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">nlargest</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">d</span><span class="o">.</span><span class="n">iteritems</span><span class="p">(),</span> <span class="n">itemgetter</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span> <span class="go">[(&#39;b&#39;, 23), (&#39;d&#39;, 17)]</span> </pre></div> </div> </section> <section id="motivation"> <h2><a class="toc-backref" href="#motivation" role="doc-backlink">Motivation</a></h2> <p>A common use of dictionaries is to count occurrences by setting the value of <code class="docutils literal notranslate"><span class="pre">d[key]</span></code> to 1 on its first occurrence, then increment the value on each subsequent occurrence. This can be done several different ways, but the <code class="docutils literal notranslate"><span class="pre">get()</span></code> method is the most succinct:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">d</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">d</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span> </pre></div> </div> <p>Once all occurrences have been counted, a common use of the resulting dictionary is to print the occurrences in occurrence-sorted order, often with the largest value first.</p> <p>This leads to a need to sort a dictionary’s items by value. The canonical method of doing so in Python is to first use <code class="docutils literal notranslate"><span class="pre">d.items()</span></code> to get a list of the dictionary’s items, then invert the ordering of each item’s tuple from (key, value) into (value, key), then sort the list; since Python sorts the list based on the first item of the tuple, the list of (inverted) items is therefore sorted by value. If desired, the list can then be reversed, and the tuples can be re-inverted back to (key, value). (However, in my experience, the inverted tuple ordering is fine for most purposes, e.g. printing out the list.)</p> <p>For example, given an occurrence count of:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;a&#39;</span><span class="p">:</span><span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">:</span><span class="mi">23</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">:</span><span class="mi">5</span><span class="p">,</span> <span class="s1">&#39;d&#39;</span><span class="p">:</span><span class="mi">17</span><span class="p">,</span> <span class="s1">&#39;e&#39;</span><span class="p">:</span><span class="mi">1</span><span class="p">}</span> </pre></div> </div> <p>we might do:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">items</span> <span class="o">=</span> <span class="p">[(</span><span class="n">v</span><span class="p">,</span> <span class="n">k</span><span class="p">)</span> <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()]</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">items</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">items</span><span class="o">.</span><span class="n">reverse</span><span class="p">()</span> <span class="c1"># so largest is first</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">items</span> <span class="o">=</span> <span class="p">[(</span><span class="n">k</span><span class="p">,</span> <span class="n">v</span><span class="p">)</span> <span class="k">for</span> <span class="n">v</span><span class="p">,</span> <span class="n">k</span> <span class="ow">in</span> <span class="n">items</span><span class="p">]</span> </pre></div> </div> <p>resulting in:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">items</span> <span class="go">[(&#39;b&#39;, 23), (&#39;d&#39;, 17), (&#39;c&#39;, 5), (&#39;a&#39;, 2), (&#39;e&#39;, 1)]</span> </pre></div> </div> <p>which shows the list in by-value order, largest first. (In this case, <code class="docutils literal notranslate"><span class="pre">'b'</span></code> was found to have the most occurrences.)</p> <p>This works fine, but is “hard to use” in two aspects. First, although this idiom is known to veteran Pythoneers, it is not at all obvious to newbies – either in terms of its algorithm (inverting the ordering of item tuples) or its implementation (using list comprehensions – which are an advanced Python feature.) Second, it requires having to repeatedly type a lot of “grunge”, resulting in both tedium and mistakes.</p> <p>We therefore would rather Python provide a method of sorting dictionaries by value which would be both easy for newbies to understand (or, better yet, not to <em>have to</em> understand) and easier for all to use.</p> </section> <section id="rationale"> <h2><a class="toc-backref" href="#rationale" role="doc-backlink">Rationale</a></h2> <p>As Tim Peters has pointed out, this sort of thing brings on the problem of trying to be all things to all people. Therefore, we will limit its scope to try to hit “the sweet spot”. Unusual cases (e.g. sorting via a custom comparison function) can, of course, be handled “manually” using present methods.</p> <p>Here are some simple possibilities:</p> <p>The <code class="docutils literal notranslate"><span class="pre">items()</span></code> method of dictionaries can be augmented with new parameters having default values that provide for full backwards-compatibility:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="n">items</span><span class="p">(</span><span class="n">sort_by_values</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="nb">reversed</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> </pre></div> </div> <p>or maybe just:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="n">items</span><span class="p">(</span><span class="n">sort_by_values</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> </pre></div> </div> <p>since reversing a list is easy enough.</p> <p>Alternatively, <code class="docutils literal notranslate"><span class="pre">items()</span></code> could simply let us control the (key, value) order:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="n">items</span><span class="p">(</span><span class="n">values_first</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> </pre></div> </div> <p>Again, this is fully backwards-compatible. It does less work than the others, but it at least eases the most complicated/tricky part of the sort-by-value problem: inverting the order of item tuples. Using this is very simple:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">items</span> <span class="o">=</span> <span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="n">items</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span> <span class="n">items</span><span class="o">.</span><span class="n">reverse</span><span class="p">()</span> <span class="c1"># (if desired)</span> </pre></div> </div> <p>The primary drawback of the preceding three approaches is the additional overhead for the parameter-less <code class="docutils literal notranslate"><span class="pre">items()</span></code> case, due to having to process default parameters. (However, if one assumes that <code class="docutils literal notranslate"><span class="pre">items()</span></code> gets used primarily for creating sort-by-value lists, this is not really a drawback in practice.)</p> <p>Alternatively, we might add a new dictionary method which somehow embodies “sorting”. This approach offers two advantages. First, it avoids adding overhead to the <code class="docutils literal notranslate"><span class="pre">items()</span></code> method. Second, it is perhaps more accessible to newbies: when they go looking for a method for sorting dictionaries, they hopefully run into this one, and they will not have to understand the finer points of tuple inversion and list sorting to achieve sort-by-value.</p> <p>To allow the four basic possibilities of sorting by key/value and in forward/reverse order, we could add this method:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="mi">4</span><span class="p">)</span> <span class="n">sorted_items</span><span class="p">(</span><span class="n">by_value</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="nb">reversed</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> </pre></div> </div> <p>I believe the most common case would actually be <code class="docutils literal notranslate"><span class="pre">by_value=1,</span> <span class="pre">reversed=1</span></code>, but the defaults values given here might lead to fewer surprises by users: <code class="docutils literal notranslate"><span class="pre">sorted_items()</span></code> would be the same as <code class="docutils literal notranslate"><span class="pre">items()</span></code> followed by <code class="docutils literal notranslate"><span class="pre">sort()</span></code>.</p> <p>Finally (as a last resort), we could use:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="mi">5</span><span class="p">)</span> <span class="n">items_sorted_by_value</span><span class="p">(</span><span class="nb">reversed</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> </pre></div> </div> </section> <section id="implementation"> <h2><a class="toc-backref" href="#implementation" role="doc-backlink">Implementation</a></h2> <p>The proposed dictionary methods would necessarily be implemented in C. Presumably, the implementation would be fairly simple since it involves just adding a few calls to Python’s existing machinery.</p> </section> <section id="concerns"> <h2><a class="toc-backref" href="#concerns" role="doc-backlink">Concerns</a></h2> <p>Aside from the run-time overhead already addressed in possibilities 1 through 3, concerns with this proposal probably will fall into the categories of “feature bloat” and/or “code bloat”. However, I believe that several of the suggestions made here will result in quite minimal bloat, resulting in a good tradeoff between bloat and “value added”.</p> <p>Tim Peters has noted that implementing this in C might not be significantly faster than implementing it in Python today. However, the major benefits intended here are “accessibility” and “ease of use”, not “speed”. Therefore, as long as it is not noticeably slower (in the case of plain <code class="docutils literal notranslate"><span class="pre">items()</span></code>, speed need not be a consideration.</p> </section> <section id="references"> <h2><a class="toc-backref" href="#references" role="doc-backlink">References</a></h2> <p>A related thread called “counting occurrences” appeared on comp.lang.python in August, 2001. This included examples of approaches to systematizing the sort-by-value problem by implementing it as reusable Python functions and classes.</p> </section> <section id="copyright"> <h2><a class="toc-backref" href="#copyright" role="doc-backlink">Copyright</a></h2> <p>This document has been placed in the public domain.</p> </section> </section> <hr class="docutils" /> <p>Source: <a class="reference external" href="https://github.com/python/peps/blob/main/peps/pep-0265.rst">https://github.com/python/peps/blob/main/peps/pep-0265.rst</a></p> <p>Last modified: <a class="reference external" href="https://github.com/python/peps/commits/main/peps/pep-0265.rst">2025-02-01 08:55:40 GMT</a></p> </article> <nav id="pep-sidebar"> <h2>Contents</h2> <ul> <li><a class="reference internal" href="#abstract">Abstract</a></li> <li><a class="reference internal" href="#bdfl-pronouncement">BDFL Pronouncement</a></li> <li><a class="reference internal" href="#motivation">Motivation</a></li> <li><a class="reference internal" href="#rationale">Rationale</a></li> <li><a class="reference internal" href="#implementation">Implementation</a></li> <li><a class="reference internal" href="#concerns">Concerns</a></li> <li><a class="reference internal" href="#references">References</a></li> <li><a class="reference internal" href="#copyright">Copyright</a></li> </ul> <br> <a id="source" href="https://github.com/python/peps/blob/main/peps/pep-0265.rst">Page Source (GitHub)</a> </nav> </section> <script src="../_static/colour_scheme.js"></script> <script src="../_static/wrap_tables.js"></script> <script src="../_static/sticky_banner.js"></script> </body> </html>

Pages: 1 2 3 4 5 6 7 8 9 10