Sophie

Sophie

distrib > Mageia > 7 > armv7hl > media > core-updates > by-pkgid > e1011ddec34cda34f3a002b121247943 > files > 712

python-docs-2.7.17-1.1.mga7.noarch.rpm


<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta charset="utf-8" />
    <title>8.3. collections — High-performance container datatypes &#8212; Python 2.7.17 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.17 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="8.4. heapq — Heap queue algorithm" href="heapq.html" />
    <link rel="prev" title="8.2. calendar — General calendar-related functions" href="calendar.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/collections.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="heapq.html" title="8.4. heapq — Heap queue algorithm"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="calendar.html" title="8.2. calendar — General calendar-related functions"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.17 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" accesskey="U">8. Data Types</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-collections">
<span id="collections-high-performance-container-datatypes"></span><h1>8.3. <a class="reference internal" href="#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> — High-performance container datatypes<a class="headerlink" href="#module-collections" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified added">New in version 2.4.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/collections.py">Lib/collections.py</a> and <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/_abcoll.py">Lib/_abcoll.py</a></p>
<hr class="docutils" />
<p>This module implements specialized container datatypes providing alternatives to
Python’s general purpose built-in containers, <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>, <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>,
<a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a>, and <a class="reference internal" href="functions.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>.</p>
<table class="docutils align-center">
<colgroup>
<col style="width: 18%" />
<col style="width: 59%" />
<col style="width: 23%" />
</colgroup>
<tbody>
<tr class="row-odd"><td><p><a class="reference internal" href="#collections.namedtuple" title="collections.namedtuple"><code class="xref py py-func docutils literal notranslate"><span class="pre">namedtuple()</span></code></a></p></td>
<td><p>factory function for creating tuple subclasses with named fields</p></td>
<td><div class="versionadded">
<p><span class="versionmodified added">New in version 2.6.</span></p>
</div>
</td>
</tr>
<tr class="row-even"><td><p><a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a></p></td>
<td><p>list-like container with fast appends and pops on either end</p></td>
<td><div class="versionadded">
<p><span class="versionmodified added">New in version 2.4.</span></p>
</div>
</td>
</tr>
<tr class="row-odd"><td><p><a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a></p></td>
<td><p>dict subclass for counting hashable objects</p></td>
<td><div class="versionadded">
<p><span class="versionmodified added">New in version 2.7.</span></p>
</div>
</td>
</tr>
<tr class="row-even"><td><p><a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a></p></td>
<td><p>dict subclass that remembers the order entries were added</p></td>
<td><div class="versionadded">
<p><span class="versionmodified added">New in version 2.7.</span></p>
</div>
</td>
</tr>
<tr class="row-odd"><td><p><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a></p></td>
<td><p>dict subclass that calls a factory function to supply missing values</p></td>
<td><div class="versionadded">
<p><span class="versionmodified added">New in version 2.5.</span></p>
</div>
</td>
</tr>
</tbody>
</table>
<p>In addition to the concrete container classes, the collections module provides
<a class="reference internal" href="#collections-abstract-base-classes"><span class="std std-ref">abstract base classes</span></a> that can be
used to test whether a class provides a particular interface, for example,
whether it is hashable or a mapping.</p>
<div class="section" id="counter-objects">
<h2>8.3.1. <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> objects<a class="headerlink" href="#counter-objects" title="Permalink to this headline">¶</a></h2>
<p>A counter tool is provided to support convenient and rapid tallies.
For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Tally occurrences of words in a list</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cnt</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">word</span> <span class="ow">in</span> <span class="p">[</span><span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="s1">&#39;green&#39;</span><span class="p">,</span> <span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="s1">&#39;blue&#39;</span><span class="p">]:</span>
<span class="gp">... </span>    <span class="n">cnt</span><span class="p">[</span><span class="n">word</span><span class="p">]</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cnt</span>
<span class="go">Counter({&#39;blue&#39;: 3, &#39;red&#39;: 2, &#39;green&#39;: 1})</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Find the ten most common words in Hamlet</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">re</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">words</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\w+&#39;</span><span class="p">,</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;hamlet.txt&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">read</span><span class="p">()</span><span class="o">.</span><span class="n">lower</span><span class="p">())</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Counter</span><span class="p">(</span><span class="n">words</span><span class="p">)</span><span class="o">.</span><span class="n">most_common</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="go">[(&#39;the&#39;, 1143), (&#39;and&#39;, 966), (&#39;to&#39;, 762), (&#39;of&#39;, 669), (&#39;i&#39;, 631),</span>
<span class="go"> (&#39;you&#39;, 554),  (&#39;a&#39;, 546), (&#39;my&#39;, 514), (&#39;hamlet&#39;, 471), (&#39;in&#39;, 451)]</span>
</pre></div>
</div>
<dl class="class">
<dt id="collections.Counter">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">Counter</code><span class="sig-paren">(</span><span class="optional">[</span><em>iterable-or-mapping</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.Counter" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> is a <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> subclass for counting hashable objects.
It is an unordered collection where elements are stored as dictionary keys
and their counts are stored as dictionary values.  Counts are allowed to be
any integer value including zero or negative counts.  The <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a>
class is similar to bags or multisets in other languages.</p>
<p>Elements are counted from an <em>iterable</em> or initialized from another
<em>mapping</em> (or counter):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">()</span>                           <span class="c1"># a new, empty counter</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="s1">&#39;gallahad&#39;</span><span class="p">)</span>                 <span class="c1"># a new counter from an iterable</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">({</span><span class="s1">&#39;red&#39;</span><span class="p">:</span> <span class="mi">4</span><span class="p">,</span> <span class="s1">&#39;blue&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">})</span>      <span class="c1"># a new counter from a mapping</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">cats</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">dogs</span><span class="o">=</span><span class="mi">8</span><span class="p">)</span>             <span class="c1"># a new counter from keyword args</span>
</pre></div>
</div>
<p>Counter objects have a dictionary interface except that they return a zero
count for missing items instead of raising a <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">([</span><span class="s1">&#39;eggs&#39;</span><span class="p">,</span> <span class="s1">&#39;ham&#39;</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s1">&#39;bacon&#39;</span><span class="p">]</span>                              <span class="c1"># count of a missing element is zero</span>
<span class="go">0</span>
</pre></div>
</div>
<p>Setting a count to zero does not remove an element from a counter.
Use <code class="docutils literal notranslate"><span class="pre">del</span></code> to remove it entirely:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s1">&#39;sausage&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">0</span>                        <span class="c1"># counter entry with a zero count</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">c</span><span class="p">[</span><span class="s1">&#39;sausage&#39;</span><span class="p">]</span>                        <span class="c1"># del actually removes the entry</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified added">New in version 2.7.</span></p>
</div>
<p>Counter objects support three methods beyond those available for all
dictionaries:</p>
<dl class="method">
<dt id="collections.Counter.elements">
<code class="descname">elements</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.Counter.elements" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an iterator over elements repeating each as many times as its
count.  Elements are returned in arbitrary order.  If an element’s count
is less than one, <a class="reference internal" href="#collections.Counter.elements" title="collections.Counter.elements"><code class="xref py py-meth docutils literal notranslate"><span class="pre">elements()</span></code></a> will ignore it.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">c</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">d</span><span class="o">=-</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="n">elements</span><span class="p">())</span>
<span class="go">[&#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;b&#39;, &#39;b&#39;]</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.Counter.most_common">
<code class="descname">most_common</code><span class="sig-paren">(</span><span class="optional">[</span><em>n</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.Counter.most_common" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of the <em>n</em> most common elements and their counts from the
most common to the least.  If <em>n</em> is omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>,
<a class="reference internal" href="#collections.Counter.most_common" title="collections.Counter.most_common"><code class="xref py py-func docutils literal notranslate"><span class="pre">most_common()</span></code></a> returns <em>all</em> elements in the counter.
Elements with equal counts are ordered arbitrarily:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Counter</span><span class="p">(</span><span class="s1">&#39;abracadabra&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">most_common</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="go">[(&#39;a&#39;, 5), (&#39;r&#39;, 2), (&#39;b&#39;, 2)]</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.Counter.subtract">
<code class="descname">subtract</code><span class="sig-paren">(</span><span class="optional">[</span><em>iterable-or-mapping</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.Counter.subtract" title="Permalink to this definition">¶</a></dt>
<dd><p>Elements are subtracted from an <em>iterable</em> or from another <em>mapping</em>
(or counter).  Like <a class="reference internal" href="stdtypes.html#dict.update" title="dict.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.update()</span></code></a> but subtracts counts instead
of replacing them.  Both inputs and outputs may be zero or negative.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">c</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">d</span><span class="o">=-</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">c</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">d</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">subtract</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span>
<span class="go">Counter({&#39;a&#39;: 3, &#39;b&#39;: 0, &#39;c&#39;: -3, &#39;d&#39;: -6})</span>
</pre></div>
</div>
</dd></dl>

<p>The usual dictionary methods are available for <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> objects
except for two which work differently for counters.</p>
<dl class="method">
<dt id="collections.Counter.fromkeys">
<code class="descname">fromkeys</code><span class="sig-paren">(</span><em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.Counter.fromkeys" title="Permalink to this definition">¶</a></dt>
<dd><p>This class method is not implemented for <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> objects.</p>
</dd></dl>

<dl class="method">
<dt id="collections.Counter.update">
<code class="descname">update</code><span class="sig-paren">(</span><span class="optional">[</span><em>iterable-or-mapping</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.Counter.update" title="Permalink to this definition">¶</a></dt>
<dd><p>Elements are counted from an <em>iterable</em> or added-in from another
<em>mapping</em> (or counter).  Like <a class="reference internal" href="stdtypes.html#dict.update" title="dict.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.update()</span></code></a> but adds counts
instead of replacing them.  Also, the <em>iterable</em> is expected to be a
sequence of elements, not a sequence of <code class="docutils literal notranslate"><span class="pre">(key,</span> <span class="pre">value)</span></code> pairs.</p>
</dd></dl>

</dd></dl>

<p>Common patterns for working with <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> objects:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">sum</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="n">values</span><span class="p">())</span>                 <span class="c1"># total of all counts</span>
<span class="n">c</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span>                       <span class="c1"># reset all counts</span>
<span class="nb">list</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>                         <span class="c1"># list unique elements</span>
<span class="nb">set</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>                          <span class="c1"># convert to a set</span>
<span class="nb">dict</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>                         <span class="c1"># convert to a regular dictionary</span>
<span class="n">c</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>                       <span class="c1"># convert to a list of (elem, cnt) pairs</span>
<span class="n">Counter</span><span class="p">(</span><span class="nb">dict</span><span class="p">(</span><span class="n">list_of_pairs</span><span class="p">))</span>    <span class="c1"># convert from a list of (elem, cnt) pairs</span>
<span class="n">c</span><span class="o">.</span><span class="n">most_common</span><span class="p">()[:</span><span class="o">-</span><span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">:</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>       <span class="c1"># n least common elements</span>
<span class="n">c</span> <span class="o">+=</span> <span class="n">Counter</span><span class="p">()</span>                  <span class="c1"># remove zero and negative counts</span>
</pre></div>
</div>
<p>Several mathematical operations are provided for combining <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a>
objects to produce multisets (counters that have counts greater than zero).
Addition and subtraction combine counters by adding or subtracting the counts
of corresponding elements.  Intersection and union return the minimum and
maximum of corresponding counts.  Each operation can accept inputs with signed
counts, but the output will exclude results with counts of zero or less.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">+</span> <span class="n">d</span>                       <span class="c1"># add two counters together:  c[x] + d[x]</span>
<span class="go">Counter({&#39;a&#39;: 4, &#39;b&#39;: 3})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">-</span> <span class="n">d</span>                       <span class="c1"># subtract (keeping only positive counts)</span>
<span class="go">Counter({&#39;a&#39;: 2})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">&amp;</span> <span class="n">d</span>                       <span class="c1"># intersection:  min(c[x], d[x])</span>
<span class="go">Counter({&#39;a&#39;: 1, &#39;b&#39;: 1})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">|</span> <span class="n">d</span>                       <span class="c1"># union:  max(c[x], d[x])</span>
<span class="go">Counter({&#39;a&#39;: 3, &#39;b&#39;: 2})</span>
</pre></div>
</div>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>Counters were primarily designed to work with positive integers to represent
running counts; however, care was taken to not unnecessarily preclude use
cases needing other types or negative values.  To help with those use cases,
this section documents the minimum range and type restrictions.</p>
<ul class="simple">
<li><p>The <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> class itself is a dictionary subclass with no
restrictions on its keys and values.  The values are intended to be numbers
representing counts, but you <em>could</em> store anything in the value field.</p></li>
<li><p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">most_common()</span></code> method requires only that the values be orderable.</p></li>
<li><p>For in-place operations such as <code class="docutils literal notranslate"><span class="pre">c[key]</span> <span class="pre">+=</span> <span class="pre">1</span></code>, the value type need only
support addition and subtraction.  So fractions, floats, and decimals would
work and negative values are supported.  The same is also true for
<code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">subtract()</span></code> which allow negative and zero values
for both inputs and outputs.</p></li>
<li><p>The multiset methods are designed only for use cases with positive values.
The inputs may be negative or zero, but only outputs with positive values
are created.  There are no type restrictions, but the value type needs to
support addition, subtraction, and comparison.</p></li>
<li><p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">elements()</span></code> method requires integer counts.  It ignores zero and
negative counts.</p></li>
</ul>
</div>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<ul>
<li><p><a class="reference external" href="https://code.activestate.com/recipes/576611/">Counter class</a>
adapted for Python 2.5 and an early <a class="reference external" href="https://code.activestate.com/recipes/259174/">Bag recipe</a> for Python 2.4.</p></li>
<li><p><a class="reference external" href="https://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html">Bag class</a>
in Smalltalk.</p></li>
<li><p>Wikipedia entry for <a class="reference external" href="https://en.wikipedia.org/wiki/Multiset">Multisets</a>.</p></li>
<li><p><a class="reference external" href="http://www.java2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm">C++ multisets</a>
tutorial with examples.</p></li>
<li><p>For mathematical operations on multisets and their use cases, see
<em>Knuth, Donald. The Art of Computer Programming Volume II,
Section 4.6.3, Exercise 19</em>.</p></li>
<li><p>To enumerate all distinct multisets of a given size over a given set of
elements, see <a class="reference internal" href="itertools.html#itertools.combinations_with_replacement" title="itertools.combinations_with_replacement"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.combinations_with_replacement()</span></code></a>.</p>
<blockquote>
<div><p>map(Counter, combinations_with_replacement(‘ABC’, 2)) –&gt; AA AB AC BB BC CC</p>
</div></blockquote>
</li>
</ul>
</div>
</div>
<div class="section" id="deque-objects">
<h2>8.3.2. <a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a> objects<a class="headerlink" href="#deque-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="collections.deque">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">deque</code><span class="sig-paren">(</span><span class="optional">[</span><em>iterable</em><span class="optional">[</span>, <em>maxlen</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new deque object initialized left-to-right (using <a class="reference internal" href="#collections.deque.append" title="collections.deque.append"><code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code></a>) with
data from <em>iterable</em>.  If <em>iterable</em> is not specified, the new deque is empty.</p>
<p>Deques are a generalization of stacks and queues (the name is pronounced “deck”
and is short for “double-ended queue”).  Deques support thread-safe, memory
efficient appends and pops from either side of the deque with approximately the
same O(1) performance in either direction.</p>
<p>Though <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code> objects support similar operations, they are optimized for
fast fixed-length operations and incur O(n) memory movement costs for
<code class="docutils literal notranslate"><span class="pre">pop(0)</span></code> and <code class="docutils literal notranslate"><span class="pre">insert(0,</span> <span class="pre">v)</span></code> operations which change both the size and
position of the underlying data representation.</p>
<div class="versionadded">
<p><span class="versionmodified added">New in version 2.4.</span></p>
</div>
<p>If <em>maxlen</em> is not specified or is <code class="docutils literal notranslate"><span class="pre">None</span></code>, deques may grow to an
arbitrary length.  Otherwise, the deque is bounded to the specified maximum
length.  Once a bounded length deque is full, when new items are added, a
corresponding number of items are discarded from the opposite end.  Bounded
length deques provide functionality similar to the <code class="docutils literal notranslate"><span class="pre">tail</span></code> filter in
Unix. They are also useful for tracking transactions and other pools of data
where only the most recent activity is of interest.</p>
<div class="versionchanged">
<p><span class="versionmodified changed">Changed in version 2.6: </span>Added <em>maxlen</em> parameter.</p>
</div>
<p>Deque objects support the following methods:</p>
<dl class="method">
<dt id="collections.deque.append">
<code class="descname">append</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.append" title="Permalink to this definition">¶</a></dt>
<dd><p>Add <em>x</em> to the right side of the deque.</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.appendleft">
<code class="descname">appendleft</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.appendleft" title="Permalink to this definition">¶</a></dt>
<dd><p>Add <em>x</em> to the left side of the deque.</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.clear">
<code class="descname">clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.clear" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove all elements from the deque leaving it with length 0.</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.count">
<code class="descname">count</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.count" title="Permalink to this definition">¶</a></dt>
<dd><p>Count the number of deque elements equal to <em>x</em>.</p>
<div class="versionadded">
<p><span class="versionmodified added">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.deque.extend">
<code class="descname">extend</code><span class="sig-paren">(</span><em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.extend" title="Permalink to this definition">¶</a></dt>
<dd><p>Extend the right side of the deque by appending elements from the iterable
argument.</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.extendleft">
<code class="descname">extendleft</code><span class="sig-paren">(</span><em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.extendleft" title="Permalink to this definition">¶</a></dt>
<dd><p>Extend the left side of the deque by appending elements from <em>iterable</em>.
Note, the series of left appends results in reversing the order of
elements in the iterable argument.</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.pop">
<code class="descname">pop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.pop" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove and return an element from the right side of the deque. If no
elements are present, raises an <a class="reference internal" href="exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.popleft">
<code class="descname">popleft</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.popleft" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove and return an element from the left side of the deque. If no
elements are present, raises an <a class="reference internal" href="exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.remove">
<code class="descname">remove</code><span class="sig-paren">(</span><em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.remove" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove the first occurrence of <em>value</em>.  If not found, raises a
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified added">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.deque.reverse">
<code class="descname">reverse</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.reverse" title="Permalink to this definition">¶</a></dt>
<dd><p>Reverse the elements of the deque in-place and then return <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified added">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.deque.rotate">
<code class="descname">rotate</code><span class="sig-paren">(</span><em>n=1</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.rotate" title="Permalink to this definition">¶</a></dt>
<dd><p>Rotate the deque <em>n</em> steps to the right.  If <em>n</em> is negative, rotate to
the left.</p>
<p>When the deque is not empty, rotating one step to the right is equivalent to
<code class="docutils literal notranslate"><span class="pre">d.appendleft(d.pop())</span></code>, and rotating one step to the left is
equivalent to <code class="docutils literal notranslate"><span class="pre">d.append(d.popleft())</span></code>.</p>
</dd></dl>

<p>Deque objects also provide one read-only attribute:</p>
<dl class="attribute">
<dt id="collections.deque.maxlen">
<code class="descname">maxlen</code><a class="headerlink" href="#collections.deque.maxlen" title="Permalink to this definition">¶</a></dt>
<dd><p>Maximum size of a deque or <code class="docutils literal notranslate"><span class="pre">None</span></code> if unbounded.</p>
<div class="versionadded">
<p><span class="versionmodified added">New in version 2.7.</span></p>
</div>
</dd></dl>

</dd></dl>

<p>In addition to the above, deques support iteration, pickling, <code class="docutils literal notranslate"><span class="pre">len(d)</span></code>,
<code class="docutils literal notranslate"><span class="pre">reversed(d)</span></code>, <code class="docutils literal notranslate"><span class="pre">copy.copy(d)</span></code>, <code class="docutils literal notranslate"><span class="pre">copy.deepcopy(d)</span></code>, membership testing with
the <a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> operator, and subscript references such as <code class="docutils literal notranslate"><span class="pre">d[-1]</span></code>.  Indexed
access is O(1) at both ends but slows to O(n) in the middle.  For fast random
access, use lists instead.</p>
<p>Example:</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">collections</span> <span class="k">import</span> <span class="n">deque</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">deque</span><span class="p">(</span><span class="s1">&#39;ghi&#39;</span><span class="p">)</span>                 <span class="c1"># make a new deque with three items</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">d</span><span class="p">:</span>                   <span class="c1"># iterate over the deque&#39;s elements</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">elem</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span>
<span class="go">G</span>
<span class="go">H</span>
<span class="go">I</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s1">&#39;j&#39;</span><span class="p">)</span>                    <span class="c1"># add a new entry to the right side</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">appendleft</span><span class="p">(</span><span class="s1">&#39;f&#39;</span><span class="p">)</span>                <span class="c1"># add a new entry to the left side</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>                                <span class="c1"># show the representation of the deque</span>
<span class="go">deque([&#39;f&#39;, &#39;g&#39;, &#39;h&#39;, &#39;i&#39;, &#39;j&#39;])</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>                          <span class="c1"># return and remove the rightmost item</span>
<span class="go">&#39;j&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>                      <span class="c1"># return and remove the leftmost item</span>
<span class="go">&#39;f&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>                          <span class="c1"># list the contents of the deque</span>
<span class="go">[&#39;g&#39;, &#39;h&#39;, &#39;i&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>                             <span class="c1"># peek at leftmost item</span>
<span class="go">&#39;g&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>                            <span class="c1"># peek at rightmost item</span>
<span class="go">&#39;i&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">reversed</span><span class="p">(</span><span class="n">d</span><span class="p">))</span>                <span class="c1"># list the contents of a deque in reverse</span>
<span class="go">[&#39;i&#39;, &#39;h&#39;, &#39;g&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;h&#39;</span> <span class="ow">in</span> <span class="n">d</span>                         <span class="c1"># search the deque</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="s1">&#39;jkl&#39;</span><span class="p">)</span>                  <span class="c1"># add multiple elements at once</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">deque([&#39;g&#39;, &#39;h&#39;, &#39;i&#39;, &#39;j&#39;, &#39;k&#39;, &#39;l&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>                      <span class="c1"># right rotation</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">deque([&#39;l&#39;, &#39;g&#39;, &#39;h&#39;, &#39;i&#39;, &#39;j&#39;, &#39;k&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span>                     <span class="c1"># left rotation</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">deque([&#39;g&#39;, &#39;h&#39;, &#39;i&#39;, &#39;j&#39;, &#39;k&#39;, &#39;l&#39;])</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">deque</span><span class="p">(</span><span class="nb">reversed</span><span class="p">(</span><span class="n">d</span><span class="p">))</span>               <span class="c1"># make a new deque in reverse order</span>
<span class="go">deque([&#39;l&#39;, &#39;k&#39;, &#39;j&#39;, &#39;i&#39;, &#39;h&#39;, &#39;g&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span>                        <span class="c1"># empty the deque</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>                          <span class="c1"># cannot pop from an empty deque</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;pyshell#6&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">-toplevel-</span>
    <span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="gr">IndexError</span>: <span class="n">pop from an empty deque</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">extendleft</span><span class="p">(</span><span class="s1">&#39;abc&#39;</span><span class="p">)</span>              <span class="c1"># extendleft() reverses the input order</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">deque([&#39;c&#39;, &#39;b&#39;, &#39;a&#39;])</span>
</pre></div>
</div>
<div class="section" id="deque-recipes">
<h3>8.3.2.1. <a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a> Recipes<a class="headerlink" href="#deque-recipes" title="Permalink to this headline">¶</a></h3>
<p>This section shows various approaches to working with deques.</p>
<p>Bounded length deques provide functionality similar to the <code class="docutils literal notranslate"><span class="pre">tail</span></code> filter
in Unix:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">tail</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">n</span><span class="o">=</span><span class="mi">10</span><span class="p">):</span>
    <span class="s1">&#39;Return the last n lines of a file&#39;</span>
    <span class="k">return</span> <span class="n">deque</span><span class="p">(</span><span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">),</span> <span class="n">n</span><span class="p">)</span>
</pre></div>
</div>
<p>Another approach to using deques is to maintain a sequence of recently
added elements by appending to the right and popping to the left:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">moving_average</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">n</span><span class="o">=</span><span class="mi">3</span><span class="p">):</span>
    <span class="c1"># moving_average([40, 30, 50, 46, 39, 44]) --&gt; 40.0 42.0 45.0 43.0</span>
    <span class="c1"># http://en.wikipedia.org/wiki/Moving_average</span>
    <span class="n">it</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
    <span class="n">d</span> <span class="o">=</span> <span class="n">deque</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">islice</span><span class="p">(</span><span class="n">it</span><span class="p">,</span> <span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">))</span>
    <span class="n">d</span><span class="o">.</span><span class="n">appendleft</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
    <span class="n">s</span> <span class="o">=</span> <span class="nb">sum</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">it</span><span class="p">:</span>
        <span class="n">s</span> <span class="o">+=</span> <span class="n">elem</span> <span class="o">-</span> <span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>
        <span class="n">d</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">elem</span><span class="p">)</span>
        <span class="k">yield</span> <span class="n">s</span> <span class="o">/</span> <span class="nb">float</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
</pre></div>
</div>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">rotate()</span></code> method provides a way to implement <a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a> slicing and
deletion.  For example, a pure Python implementation of <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">d[n]</span></code> relies on
the <code class="xref py py-meth docutils literal notranslate"><span class="pre">rotate()</span></code> method to position elements to be popped:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">delete_nth</span><span class="p">(</span><span class="n">d</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
    <span class="n">d</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="o">-</span><span class="n">n</span><span class="p">)</span>
    <span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>
    <span class="n">d</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
</pre></div>
</div>
<p>To implement <a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a> slicing, use a similar approach applying
<code class="xref py py-meth docutils literal notranslate"><span class="pre">rotate()</span></code> to bring a target element to the left side of the deque. Remove
old entries with <code class="xref py py-meth docutils literal notranslate"><span class="pre">popleft()</span></code>, add new entries with <code class="xref py py-meth docutils literal notranslate"><span class="pre">extend()</span></code>, and then
reverse the rotation.
With minor variations on that approach, it is easy to implement Forth style
stack manipulations such as <code class="docutils literal notranslate"><span class="pre">dup</span></code>, <code class="docutils literal notranslate"><span class="pre">drop</span></code>, <code class="docutils literal notranslate"><span class="pre">swap</span></code>, <code class="docutils literal notranslate"><span class="pre">over</span></code>, <code class="docutils literal notranslate"><span class="pre">pick</span></code>,
<code class="docutils literal notranslate"><span class="pre">rot</span></code>, and <code class="docutils literal notranslate"><span class="pre">roll</span></code>.</p>
</div>
</div>
<div class="section" id="defaultdict-objects">
<h2>8.3.3. <a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> objects<a class="headerlink" href="#defaultdict-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="collections.defaultdict">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">defaultdict</code><span class="sig-paren">(</span><span class="optional">[</span><em>default_factory</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.defaultdict" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new dictionary-like object.  <a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> is a subclass of the
built-in <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> class.  It overrides one method and adds one writable
instance variable.  The remaining functionality is the same as for the
<a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> class and is not documented here.</p>
<p>The first argument provides the initial value for the <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a>
attribute; it defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code>. All remaining arguments are treated the same
as if they were passed to the <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> constructor, including keyword
arguments.</p>
<div class="versionadded">
<p><span class="versionmodified added">New in version 2.5.</span></p>
</div>
<p><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> objects support the following method in addition to the
standard <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> operations:</p>
<dl class="method">
<dt id="collections.defaultdict.__missing__">
<code class="descname">__missing__</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.defaultdict.__missing__" title="Permalink to this definition">¶</a></dt>
<dd><p>If the <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> attribute is <code class="docutils literal notranslate"><span class="pre">None</span></code>, this raises a
<a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> exception with the <em>key</em> as argument.</p>
<p>If <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it is called without arguments
to provide a default value for the given <em>key</em>, this value is inserted in
the dictionary for the <em>key</em>, and returned.</p>
<p>If calling <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> raises an exception this exception is
propagated unchanged.</p>
<p>This method is called by the <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> method of the
<a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> class when the requested key is not found; whatever it
returns or raises is then returned or raised by <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>.</p>
<p>Note that <a class="reference internal" href="#collections.defaultdict.__missing__" title="collections.defaultdict.__missing__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__missing__()</span></code></a> is <em>not</em> called for any operations besides
<a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>. This means that <code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code> will, like normal
dictionaries, return <code class="docutils literal notranslate"><span class="pre">None</span></code> as a default rather than using
<a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a>.</p>
</dd></dl>

<p><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> objects support the following instance variable:</p>
<dl class="attribute">
<dt id="collections.defaultdict.default_factory">
<code class="descname">default_factory</code><a class="headerlink" href="#collections.defaultdict.default_factory" title="Permalink to this definition">¶</a></dt>
<dd><p>This attribute is used by the <a class="reference internal" href="#collections.defaultdict.__missing__" title="collections.defaultdict.__missing__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__missing__()</span></code></a> method; it is
initialized from the first argument to the constructor, if present, or to
<code class="docutils literal notranslate"><span class="pre">None</span></code>, if absent.</p>
</dd></dl>

</dd></dl>

<div class="section" id="defaultdict-examples">
<h3>8.3.3.1. <a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> Examples<a class="headerlink" href="#defaultdict-examples" title="Permalink to this headline">¶</a></h3>
<p>Using <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code> as the <code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code>, it is easy to group a
sequence of key-value pairs into a dictionary of lists:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">&#39;yellow&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;yellow&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="nb">list</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </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">s</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">d</span><span class="p">[</span><span class="n">k</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">v</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>
<span class="go">[(&#39;blue&#39;, [2, 4]), (&#39;red&#39;, [1]), (&#39;yellow&#39;, [1, 3])]</span>
</pre></div>
</div>
<p>When each key is encountered for the first time, it is not already in the
mapping; so an entry is automatically created using the <code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code>
function which returns an empty <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>.  The <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.append()</span></code>
operation then attaches the value to the new list.  When keys are encountered
again, the look-up proceeds normally (returning the list for that key) and the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">list.append()</span></code> operation adds another value to the list. This technique is
simpler and faster than an equivalent technique using <a class="reference internal" href="stdtypes.html#dict.setdefault" title="dict.setdefault"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.setdefault()</span></code></a>:</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="gp">&gt;&gt;&gt; </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">s</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">d</span><span class="o">.</span><span class="n">setdefault</span><span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="p">[])</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">v</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>
<span class="go">[(&#39;blue&#39;, [2, 4]), (&#39;red&#39;, [1]), (&#39;yellow&#39;, [1, 3])]</span>
</pre></div>
</div>
<p>Setting the <code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code> to <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> makes the
<a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> useful for counting (like a bag or multiset in other
languages):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;mississippi&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">d</span><span class="p">[</span><span class="n">k</span><span class="p">]</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>
<span class="go">[(&#39;i&#39;, 4), (&#39;p&#39;, 2), (&#39;s&#39;, 4), (&#39;m&#39;, 1)]</span>
</pre></div>
</div>
<p>When a letter is first encountered, it is missing from the mapping, so the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code> function calls <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> to supply a default count of
zero.  The increment operation then builds up the count for each letter.</p>
<p>The function <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> which always returns zero is just a special case of
constant functions.  A faster and more flexible way to create constant functions
is to use <a class="reference internal" href="itertools.html#itertools.repeat" title="itertools.repeat"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.repeat()</span></code></a> which can supply any constant value (not just
zero):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">constant_factory</span><span class="p">(</span><span class="n">value</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">itertools</span><span class="o">.</span><span class="n">repeat</span><span class="p">(</span><span class="n">value</span><span class="p">)</span><span class="o">.</span><span class="n">next</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="n">constant_factory</span><span class="p">(</span><span class="s1">&#39;&lt;missing&gt;&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;John&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;ran&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">%(name)s</span><span class="s1"> </span><span class="si">%(action)s</span><span class="s1"> to </span><span class="si">%(object)s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">d</span>
<span class="go">&#39;John ran to &lt;missing&gt;&#39;</span>
</pre></div>
</div>
<p>Setting the <code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code> to <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> makes the
<a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> useful for building a dictionary of sets:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="mi">4</span><span class="p">)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="nb">set</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </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">s</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">d</span><span class="p">[</span><span class="n">k</span><span class="p">]</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">v</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>
<span class="go">[(&#39;blue&#39;, set([2, 4])), (&#39;red&#39;, set([1, 3]))]</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="namedtuple-factory-function-for-tuples-with-named-fields">
<h2>8.3.4. <a class="reference internal" href="#collections.namedtuple" title="collections.namedtuple"><code class="xref py py-func docutils literal notranslate"><span class="pre">namedtuple()</span></code></a> Factory Function for Tuples with Named Fields<a class="headerlink" href="#namedtuple-factory-function-for-tuples-with-named-fields" title="Permalink to this headline">¶</a></h2>
<p>Named tuples assign meaning to each position in a tuple and allow for more readable,
self-documenting code.  They can be used wherever regular tuples are used, and
they add the ability to access fields by name instead of position index.</p>
<dl class="function">
<dt id="collections.namedtuple">
<code class="descclassname">collections.</code><code class="descname">namedtuple</code><span class="sig-paren">(</span><em>typename</em>, <em>field_names</em><span class="optional">[</span>, <em>verbose=False</em><span class="optional">]</span><span class="optional">[</span>, <em>rename=False</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.namedtuple" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new tuple subclass named <em>typename</em>.  The new subclass is used to
create tuple-like objects that have fields accessible by attribute lookup as
well as being indexable and iterable.  Instances of the subclass also have a
helpful docstring (with typename and field_names) and a helpful <a class="reference internal" href="../reference/datamodel.html#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__repr__()</span></code></a>
method which lists the tuple contents in a <code class="docutils literal notranslate"><span class="pre">name=value</span></code> format.</p>
<p>The <em>field_names</em> are a sequence of strings such as <code class="docutils literal notranslate"><span class="pre">['x',</span> <span class="pre">'y']</span></code>.
Alternatively, <em>field_names</em> can be a single string with each fieldname
separated by whitespace and/or commas, for example <code class="docutils literal notranslate"><span class="pre">'x</span> <span class="pre">y'</span></code> or <code class="docutils literal notranslate"><span class="pre">'x,</span> <span class="pre">y'</span></code>.</p>
<p>Any valid Python identifier may be used for a fieldname except for names
starting with an underscore.  Valid identifiers consist of letters, digits,
and underscores but do not start with a digit or underscore and cannot be
a <a class="reference internal" href="keyword.html#module-keyword" title="keyword: Test whether a string is a keyword in Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">keyword</span></code></a> such as <em>class</em>, <em>for</em>, <em>return</em>, <em>global</em>, <em>pass</em>, <em>print</em>,
or <em>raise</em>.</p>
<p>If <em>rename</em> is true, invalid fieldnames are automatically replaced
with positional names.  For example, <code class="docutils literal notranslate"><span class="pre">['abc',</span> <span class="pre">'def',</span> <span class="pre">'ghi',</span> <span class="pre">'abc']</span></code> is
converted to <code class="docutils literal notranslate"><span class="pre">['abc',</span> <span class="pre">'_1',</span> <span class="pre">'ghi',</span> <span class="pre">'_3']</span></code>, eliminating the keyword
<code class="docutils literal notranslate"><span class="pre">def</span></code> and the duplicate fieldname <code class="docutils literal notranslate"><span class="pre">abc</span></code>.</p>
<p>If <em>verbose</em> is true, the class definition is printed just before being built.</p>
<p>Named tuple instances do not have per-instance dictionaries, so they are
lightweight and require no more memory than regular tuples.</p>
<div class="versionadded">
<p><span class="versionmodified added">New in version 2.6.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">Changed in version 2.7: </span>added support for <em>rename</em>.</p>
</div>
</dd></dl>

<p>Example:</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Point</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Point&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;x&#39;</span><span class="p">,</span> <span class="s1">&#39;y&#39;</span><span class="p">],</span> <span class="n">verbose</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="go">class Point(tuple):</span>
<span class="go">    &#39;Point(x, y)&#39;</span>

<span class="go">    __slots__ = ()</span>

<span class="go">    _fields = (&#39;x&#39;, &#39;y&#39;)</span>

<span class="go">    def __new__(_cls, x, y):</span>
<span class="go">        &#39;Create new instance of Point(x, y)&#39;</span>
<span class="go">        return _tuple.__new__(_cls, (x, y))</span>

<span class="go">    @classmethod</span>
<span class="go">    def _make(cls, iterable, new=tuple.__new__, len=len):</span>
<span class="go">        &#39;Make a new Point object from a sequence or iterable&#39;</span>
<span class="go">        result = new(cls, iterable)</span>
<span class="go">        if len(result) != 2:</span>
<span class="go">            raise TypeError(&#39;Expected 2 arguments, got %d&#39; % len(result))</span>
<span class="go">        return result</span>

<span class="go">    def __repr__(self):</span>
<span class="go">        &#39;Return a nicely formatted representation string&#39;</span>
<span class="go">        return &#39;Point(x=%r, y=%r)&#39; % self</span>

<span class="go">    def _asdict(self):</span>
<span class="go">        &#39;Return a new OrderedDict which maps field names to their values&#39;</span>
<span class="go">        return OrderedDict(zip(self._fields, self))</span>

<span class="go">    def _replace(_self, **kwds):</span>
<span class="go">        &#39;Return a new Point object replacing specified fields with new values&#39;</span>
<span class="go">        result = _self._make(map(kwds.pop, (&#39;x&#39;, &#39;y&#39;), _self))</span>
<span class="go">        if kwds:</span>
<span class="go">            raise ValueError(&#39;Got unexpected field names: %r&#39; % kwds.keys())</span>
<span class="go">        return result</span>

<span class="go">    def __getnewargs__(self):</span>
<span class="go">        &#39;Return self as a plain tuple.  Used by copy and pickle.&#39;</span>
<span class="go">        return tuple(self)</span>

<span class="go">    __dict__ = _property(_asdict)</span>

<span class="go">    def __getstate__(self):</span>
<span class="go">        &#39;Exclude the OrderedDict from pickling&#39;</span>
<span class="go">        pass</span>

<span class="go">    x = _property(_itemgetter(0), doc=&#39;Alias for field number 0&#39;)</span>

<span class="go">    y = _property(_itemgetter(1), doc=&#39;Alias for field number 1&#39;)</span>



<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">Point</span><span class="p">(</span><span class="mi">11</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="mi">22</span><span class="p">)</span>     <span class="c1"># instantiate with positional or keyword arguments</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">+</span> <span class="n">p</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>             <span class="c1"># indexable like the plain tuple (11, 22)</span>
<span class="go">33</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="n">p</span>                <span class="c1"># unpack like a regular tuple</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="p">,</span> <span class="n">y</span>
<span class="go">(11, 22)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">x</span> <span class="o">+</span> <span class="n">p</span><span class="o">.</span><span class="n">y</span>               <span class="c1"># fields also accessible by name</span>
<span class="go">33</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span>                       <span class="c1"># readable __repr__ with a name=value style</span>
<span class="go">Point(x=11, y=22)</span>
</pre></div>
</div>
<p>Named tuples are especially useful for assigning field names to result tuples returned
by the <a class="reference internal" href="csv.html#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> or <a class="reference internal" href="sqlite3.html#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> modules:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">EmployeeRecord</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;EmployeeRecord&#39;</span><span class="p">,</span> <span class="s1">&#39;name, age, title, department, paygrade&#39;</span><span class="p">)</span>

<span class="kn">import</span> <span class="nn">csv</span>
<span class="k">for</span> <span class="n">emp</span> <span class="ow">in</span> <span class="nb">map</span><span class="p">(</span><span class="n">EmployeeRecord</span><span class="o">.</span><span class="n">_make</span><span class="p">,</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="nb">open</span><span class="p">(</span><span class="s2">&quot;employees.csv&quot;</span><span class="p">,</span> <span class="s2">&quot;rb&quot;</span><span class="p">))):</span>
    <span class="nb">print</span> <span class="n">emp</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">emp</span><span class="o">.</span><span class="n">title</span>

<span class="kn">import</span> <span class="nn">sqlite3</span>
<span class="n">conn</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s1">&#39;/companydata&#39;</span><span class="p">)</span>
<span class="n">cursor</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;SELECT name, age, title, department, paygrade FROM employees&#39;</span><span class="p">)</span>
<span class="k">for</span> <span class="n">emp</span> <span class="ow">in</span> <span class="nb">map</span><span class="p">(</span><span class="n">EmployeeRecord</span><span class="o">.</span><span class="n">_make</span><span class="p">,</span> <span class="n">cursor</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()):</span>
    <span class="nb">print</span> <span class="n">emp</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">emp</span><span class="o">.</span><span class="n">title</span>
</pre></div>
</div>
<p>In addition to the methods inherited from tuples, named tuples support
three additional methods and one attribute.  To prevent conflicts with
field names, the method and attribute names start with an underscore.</p>
<dl class="classmethod">
<dt id="collections.somenamedtuple._make">
<em class="property">classmethod </em><code class="descclassname">somenamedtuple.</code><code class="descname">_make</code><span class="sig-paren">(</span><em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.somenamedtuple._make" title="Permalink to this definition">¶</a></dt>
<dd><p>Class method that makes a new instance from an existing sequence or iterable.</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="p">[</span><span class="mi">11</span><span class="p">,</span> <span class="mi">22</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Point</span><span class="o">.</span><span class="n">_make</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
<span class="go">Point(x=11, y=22)</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.somenamedtuple._asdict">
<code class="descclassname">somenamedtuple.</code><code class="descname">_asdict</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.somenamedtuple._asdict" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> which maps field names to their corresponding
values:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">Point</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="mi">11</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="mi">22</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">_asdict</span><span class="p">()</span>
<span class="go">OrderedDict([(&#39;x&#39;, 11), (&#39;y&#39;, 22)])</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">Changed in version 2.7: </span>Returns an <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> instead of a regular <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.somenamedtuple._replace">
<code class="descclassname">somenamedtuple.</code><code class="descname">_replace</code><span class="sig-paren">(</span><em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.somenamedtuple._replace" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new instance of the named tuple replacing specified fields with new
values:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">Point</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="mi">11</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="mi">22</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="mi">33</span><span class="p">)</span>
<span class="go">Point(x=33, y=22)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">partnum</span><span class="p">,</span> <span class="n">record</span> <span class="ow">in</span> <span class="n">inventory</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
<span class="gp">... </span>    <span class="n">inventory</span><span class="p">[</span><span class="n">partnum</span><span class="p">]</span> <span class="o">=</span> <span class="n">record</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="n">price</span><span class="o">=</span><span class="n">newprices</span><span class="p">[</span><span class="n">partnum</span><span class="p">],</span> <span class="n">timestamp</span><span class="o">=</span><span class="n">time</span><span class="o">.</span><span class="n">now</span><span class="p">())</span>
</pre></div>
</div>
</dd></dl>

<dl class="attribute">
<dt id="collections.somenamedtuple._fields">
<code class="descclassname">somenamedtuple.</code><code class="descname">_fields</code><a class="headerlink" href="#collections.somenamedtuple._fields" title="Permalink to this definition">¶</a></dt>
<dd><p>Tuple of strings listing the field names.  Useful for introspection
and for creating new named tuple types from existing named tuples.</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">_fields</span>            <span class="c1"># view the field names</span>
<span class="go">(&#39;x&#39;, &#39;y&#39;)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Color</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Color&#39;</span><span class="p">,</span> <span class="s1">&#39;red green blue&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Pixel</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Pixel&#39;</span><span class="p">,</span> <span class="n">Point</span><span class="o">.</span><span class="n">_fields</span> <span class="o">+</span> <span class="n">Color</span><span class="o">.</span><span class="n">_fields</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Pixel</span><span class="p">(</span><span class="mi">11</span><span class="p">,</span> <span class="mi">22</span><span class="p">,</span> <span class="mi">128</span><span class="p">,</span> <span class="mi">255</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
<span class="go">Pixel(x=11, y=22, red=128, green=255, blue=0)</span>
</pre></div>
</div>
</dd></dl>

<p>To retrieve a field whose name is stored in a string, use the <a class="reference internal" href="functions.html#getattr" title="getattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">getattr()</span></code></a>
function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">getattr</span><span class="p">(</span><span class="n">p</span><span class="p">,</span> <span class="s1">&#39;x&#39;</span><span class="p">)</span>
<span class="go">11</span>
</pre></div>
</div>
<p>To convert a dictionary to a named tuple, use the double-star-operator
(as described in <a class="reference internal" href="../tutorial/controlflow.html#tut-unpacking-arguments"><span class="std std-ref">Unpacking Argument Lists</span></a>):</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;x&#39;</span><span class="p">:</span> <span class="mi">11</span><span class="p">,</span> <span class="s1">&#39;y&#39;</span><span class="p">:</span> <span class="mi">22</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Point</span><span class="p">(</span><span class="o">**</span><span class="n">d</span><span class="p">)</span>
<span class="go">Point(x=11, y=22)</span>
</pre></div>
</div>
<p>Since a named tuple is a regular Python class, it is easy to add or change
functionality with a subclass.  Here is how to add a calculated field and
a fixed-width print format:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Point</span><span class="p">(</span><span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Point&#39;</span><span class="p">,</span> <span class="s1">&#39;x y&#39;</span><span class="p">)):</span>
<span class="gp">... </span>    <span class="vm">__slots__</span> <span class="o">=</span> <span class="p">()</span>
<span class="gp">... </span>    <span class="nd">@property</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">hypot</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">x</span> <span class="o">**</span> <span class="mi">2</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span> <span class="o">**</span> <span class="mi">2</span><span class="p">)</span> <span class="o">**</span> <span class="mf">0.5</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="s1">&#39;Point: x=</span><span class="si">%6.3f</span><span class="s1">  y=</span><span class="si">%6.3f</span><span class="s1">  hypot=</span><span class="si">%6.3f</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">hypot</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">Point</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="n">Point</span><span class="p">(</span><span class="mi">14</span><span class="p">,</span> <span class="mi">5</span><span class="o">/</span><span class="mf">7.</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">p</span>
<span class="go">Point: x= 3.000  y= 4.000  hypot= 5.000</span>
<span class="go">Point: x=14.000  y= 0.714  hypot=14.018</span>
</pre></div>
</div>
<p>The subclass shown above sets <code class="docutils literal notranslate"><span class="pre">__slots__</span></code> to an empty tuple.  This helps
keep memory requirements low by preventing the creation of instance dictionaries.</p>
<p>Subclassing is not useful for adding new, stored fields.  Instead, simply
create a new named tuple type from the <code class="xref py py-attr docutils literal notranslate"><span class="pre">_fields</span></code> attribute:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Point3D</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Point3D&#39;</span><span class="p">,</span> <span class="n">Point</span><span class="o">.</span><span class="n">_fields</span> <span class="o">+</span> <span class="p">(</span><span class="s1">&#39;z&#39;</span><span class="p">,))</span>
</pre></div>
</div>
<p>Default values can be implemented by using <code class="xref py py-meth docutils literal notranslate"><span class="pre">_replace()</span></code> to
customize a prototype instance:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Account</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Account&#39;</span><span class="p">,</span> <span class="s1">&#39;owner balance transaction_count&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">default_account</span> <span class="o">=</span> <span class="n">Account</span><span class="p">(</span><span class="s1">&#39;&lt;owner name&gt;&#39;</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">johns_account</span> <span class="o">=</span> <span class="n">default_account</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="n">owner</span><span class="o">=</span><span class="s1">&#39;John&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Enumerated constants can be implemented with named tuples, but it is simpler
and more efficient to use a simple class declaration:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Status</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Status&#39;</span><span class="p">,</span> <span class="s1">&#39;open pending closed&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">_make</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Status</span><span class="o">.</span><span class="n">open</span><span class="p">,</span> <span class="n">Status</span><span class="o">.</span><span class="n">pending</span><span class="p">,</span> <span class="n">Status</span><span class="o">.</span><span class="n">closed</span>
<span class="go">(0, 1, 2)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Status</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">open</span><span class="p">,</span> <span class="n">pending</span><span class="p">,</span> <span class="n">closed</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<p><a class="reference external" href="https://code.activestate.com/recipes/500261/">Named tuple recipe</a>
adapted for Python 2.4.</p>
</div>
</div>
<div class="section" id="ordereddict-objects">
<h2>8.3.5. <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> objects<a class="headerlink" href="#ordereddict-objects" title="Permalink to this headline">¶</a></h2>
<p>Ordered dictionaries are just like regular dictionaries but they remember the
order that items were inserted.  When iterating over an ordered dictionary,
the items are returned in the order their keys were first added.</p>
<dl class="class">
<dt id="collections.OrderedDict">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">OrderedDict</code><span class="sig-paren">(</span><span class="optional">[</span><em>items</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.OrderedDict" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an instance of a dict subclass, supporting the usual <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>
methods.  An <em>OrderedDict</em> is a dict that remembers the order that keys
were first inserted. If a new entry overwrites an existing entry, the
original insertion position is left unchanged.  Deleting an entry and
reinserting it will move it to the end.</p>
<div class="versionadded">
<p><span class="versionmodified added">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.OrderedDict.popitem">
<code class="descclassname">OrderedDict.</code><code class="descname">popitem</code><span class="sig-paren">(</span><em>last=True</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.OrderedDict.popitem" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#collections.OrderedDict.popitem" title="collections.OrderedDict.popitem"><code class="xref py py-meth docutils literal notranslate"><span class="pre">popitem()</span></code></a> method for ordered dictionaries returns and removes
a (key, value) pair.  The pairs are returned in LIFO order if <em>last</em> is
true or FIFO order if false.</p>
</dd></dl>

<p>In addition to the usual mapping methods, ordered dictionaries also support
reverse iteration using <a class="reference internal" href="functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal notranslate"><span class="pre">reversed()</span></code></a>.</p>
<p>Equality tests between <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> objects are order-sensitive
and are implemented as <code class="docutils literal notranslate"><span class="pre">list(od1.items())==list(od2.items())</span></code>.
Equality tests between <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> objects and other
<a class="reference internal" href="#collections.Mapping" title="collections.Mapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mapping</span></code></a> objects are order-insensitive like regular
dictionaries.  This allows <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> objects to be substituted
anywhere a regular dictionary is used.</p>
<p>The <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> constructor and <code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code> method both accept
keyword arguments, but their order is lost because Python’s function call
semantics pass-in keyword arguments using a regular unordered dictionary.</p>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<p><a class="reference external" href="https://code.activestate.com/recipes/576693/">Equivalent OrderedDict recipe</a>
that runs on Python 2.4 or later.</p>
</div>
<div class="section" id="ordereddict-examples-and-recipes">
<h3>8.3.5.1. <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> Examples and Recipes<a class="headerlink" href="#ordereddict-examples-and-recipes" title="Permalink to this headline">¶</a></h3>
<p>Since an ordered dictionary remembers its insertion order, it can be used
in conjunction with sorting to make a sorted dictionary:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># regular unsorted dictionary</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;banana&#39;</span><span class="p">:</span> <span class="mi">3</span><span class="p">,</span> <span class="s1">&#39;apple&#39;</span><span class="p">:</span> <span class="mi">4</span><span class="p">,</span> <span class="s1">&#39;pear&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;orange&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">}</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># dictionary sorted by key</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">OrderedDict</span><span class="p">(</span><span class="nb">sorted</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">(),</span> <span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">t</span><span class="p">:</span> <span class="n">t</span><span class="p">[</span><span class="mi">0</span><span class="p">]))</span>
<span class="go">OrderedDict([(&#39;apple&#39;, 4), (&#39;banana&#39;, 3), (&#39;orange&#39;, 2), (&#39;pear&#39;, 1)])</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># dictionary sorted by value</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">OrderedDict</span><span class="p">(</span><span class="nb">sorted</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">(),</span> <span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">t</span><span class="p">:</span> <span class="n">t</span><span class="p">[</span><span class="mi">1</span><span class="p">]))</span>
<span class="go">OrderedDict([(&#39;pear&#39;, 1), (&#39;orange&#39;, 2), (&#39;banana&#39;, 3), (&#39;apple&#39;, 4)])</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># dictionary sorted by length of the key string</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">OrderedDict</span><span class="p">(</span><span class="nb">sorted</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">(),</span> <span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">t</span><span class="p">:</span> <span class="nb">len</span><span class="p">(</span><span class="n">t</span><span class="p">[</span><span class="mi">0</span><span class="p">])))</span>
<span class="go">OrderedDict([(&#39;pear&#39;, 1), (&#39;apple&#39;, 4), (&#39;orange&#39;, 2), (&#39;banana&#39;, 3)])</span>
</pre></div>
</div>
<p>The new sorted dictionaries maintain their sort order when entries
are deleted.  But when new keys are added, the keys are appended
to the end and the sort is not maintained.</p>
<p>It is also straight-forward to create an ordered dictionary variant
that remembers the order the keys were <em>last</em> inserted.
If a new entry overwrites an existing entry, the
original insertion position is changed and moved to the end:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">LastUpdatedOrderedDict</span><span class="p">(</span><span class="n">OrderedDict</span><span class="p">):</span>
    <span class="s1">&#39;Store items in the order the keys were last added&#39;</span>

    <span class="k">def</span> <span class="nf">__setitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">key</span> <span class="ow">in</span> <span class="bp">self</span><span class="p">:</span>
            <span class="k">del</span> <span class="bp">self</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
        <span class="n">OrderedDict</span><span class="o">.</span><span class="fm">__setitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
</pre></div>
</div>
<p>An ordered dictionary can be combined with the <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> class
so that the counter remembers the order elements are first encountered:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">OrderedCounter</span><span class="p">(</span><span class="n">Counter</span><span class="p">,</span> <span class="n">OrderedDict</span><span class="p">):</span>
     <span class="s1">&#39;Counter that remembers the order elements are first encountered&#39;</span>

     <span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
         <span class="k">return</span> <span class="s1">&#39;</span><span class="si">%s</span><span class="s1">(</span><span class="si">%r</span><span class="s1">)&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="vm">__class__</span><span class="o">.</span><span class="vm">__name__</span><span class="p">,</span> <span class="n">OrderedDict</span><span class="p">(</span><span class="bp">self</span><span class="p">))</span>

     <span class="k">def</span> <span class="nf">__reduce__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
         <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="vm">__class__</span><span class="p">,</span> <span class="p">(</span><span class="n">OrderedDict</span><span class="p">(</span><span class="bp">self</span><span class="p">),)</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="collections-abstract-base-classes">
<span id="id1"></span><h2>8.3.6. Collections Abstract Base Classes<a class="headerlink" href="#collections-abstract-base-classes" title="Permalink to this headline">¶</a></h2>
<p>The collections module offers the following <a class="reference internal" href="../glossary.html#term-abstract-base-class"><span class="xref std std-term">ABCs</span></a>:</p>
<table class="docutils align-center">
<colgroup>
<col style="width: 21%" />
<col style="width: 18%" />
<col style="width: 18%" />
<col style="width: 43%" />
</colgroup>
<thead>
<tr class="row-odd"><th class="head"><p>ABC</p></th>
<th class="head"><p>Inherits from</p></th>
<th class="head"><p>Abstract Methods</p></th>
<th class="head"><p>Mixin Methods</p></th>
</tr>
</thead>
<tbody>
<tr class="row-even"><td><p><a class="reference internal" href="#collections.Container" title="collections.Container"><code class="xref py py-class docutils literal notranslate"><span class="pre">Container</span></code></a></p></td>
<td></td>
<td><p><code class="docutils literal notranslate"><span class="pre">__contains__</span></code></p></td>
<td></td>
</tr>
<tr class="row-odd"><td><p><a class="reference internal" href="#collections.Hashable" title="collections.Hashable"><code class="xref py py-class docutils literal notranslate"><span class="pre">Hashable</span></code></a></p></td>
<td></td>
<td><p><code class="docutils literal notranslate"><span class="pre">__hash__</span></code></p></td>
<td></td>
</tr>
<tr class="row-even"><td><p><a class="reference internal" href="#collections.Iterable" title="collections.Iterable"><code class="xref py py-class docutils literal notranslate"><span class="pre">Iterable</span></code></a></p></td>
<td></td>
<td><p><code class="docutils literal notranslate"><span class="pre">__iter__</span></code></p></td>
<td></td>
</tr>
<tr class="row-odd"><td><p><a class="reference internal" href="#collections.Iterator" title="collections.Iterator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Iterator</span></code></a></p></td>
<td><p><a class="reference internal" href="#collections.Iterable" title="collections.Iterable"><code class="xref py py-class docutils literal notranslate"><span class="pre">Iterable</span></code></a></p></td>
<td><p><code class="docutils literal notranslate"><span class="pre">next</span></code></p></td>
<td><p><code class="docutils literal notranslate"><span class="pre">__iter__</span></code></p></td>
</tr>
<tr class="row-even"><td><p><a class="reference internal" href="#collections.Sized" title="collections.Sized"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sized</span></code></a></p></td>
<td></td>
<td><p><code class="docutils literal notranslate"><span class="pre">__len__</span></code></p></td>
<td></td>
</tr>
<tr class="row-odd"><td><p><a class="reference internal" href="#collections.Callable" title="collections.Callable"><code class="xref py py-class docutils literal notranslate"><span class="pre">Callable</span></code></a></p></td>
<td></td>
<td><p><code class="docutils literal notranslate"><span class="pre">__call__</span></code></p></td>
<td></td>
</tr>
<tr class="row-even"><td><p><a class="reference internal" href="#collections.Sequence" title="collections.Sequence"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sequence</span></code></a></p></td>
<td><p><a class="reference internal" href="#collections.Sized" title="collections.Sized"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sized</span></code></a>,
<a class="reference internal" href="#collections.Iterable" title="collections.Iterable"><code class="xref py py-class docutils literal notranslate"><span class="pre">Iterable</span></code></a>,
<a class="reference internal" href="#collections.Container" title="collections.Container"><code class="xref py py-class docutils literal notranslate"><span class="pre">Container</span></code></a></p></td>
<td><p><code class="docutils literal notranslate"><span class="pre">__getitem__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__len__</span></code></p></td>
<td><p><code class="docutils literal notranslate"><span class="pre">__contains__</span></code>, <code class="docutils literal notranslate"><span class="pre">__iter__</span></code>, <code class="docutils literal notranslate"><span class="pre">__reversed__</span></code>,
<code class="docutils literal notranslate"><span class="pre">index</span></code>, and <code class="docutils literal notranslate"><span class="pre">count</span></code></p></td>
</tr>
<tr class="row-odd"><td><p><a class="reference internal" href="#collections.MutableSequence" title="collections.MutableSequence"><code class="xref py py-class docutils literal notranslate"><span class="pre">MutableSequence</span></code></a></p></td>
<td><p><a class="reference internal" href="#collections.Sequence" title="collections.Sequence"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sequence</span></code></a></p></td>
<td><p><code class="docutils literal notranslate"><span class="pre">__getitem__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__setitem__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__delitem__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__len__</span></code>,
<code class="docutils literal notranslate"><span class="pre">insert</span></code></p></td>
<td><p>Inherited <a class="reference internal" href="#collections.Sequence" title="collections.Sequence"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sequence</span></code></a> methods and
<code class="docutils literal notranslate"><span class="pre">append</span></code>, <code class="docutils literal notranslate"><span class="pre">reverse</span></code>, <code class="docutils literal notranslate"><span class="pre">extend</span></code>, <code class="docutils literal notranslate"><span class="pre">pop</span></code>,
<code class="docutils literal notranslate"><span class="pre">remove</span></code>, and <code class="docutils literal notranslate"><span class="pre">__iadd__</span></code></p></td>
</tr>
<tr class="row-even"><td><p><a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a></p></td>
<td><p><a class="reference internal" href="#collections.Sized" title="collections.Sized"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sized</span></code></a>,
<a class="reference internal" href="#collections.Iterable" title="collections.Iterable"><code class="xref py py-class docutils literal notranslate"><span class="pre">Iterable</span></code></a>,
<a class="reference internal" href="#collections.Container" title="collections.Container"><code class="xref py py-class docutils literal notranslate"><span class="pre">Container</span></code></a></p></td>
<td><p><code class="docutils literal notranslate"><span class="pre">__contains__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__iter__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__len__</span></code></p></td>
<td><p><code class="docutils literal notranslate"><span class="pre">__le__</span></code>, <code class="docutils literal notranslate"><span class="pre">__lt__</span></code>, <code class="docutils literal notranslate"><span class="pre">__eq__</span></code>, <code class="docutils literal notranslate"><span class="pre">__ne__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__gt__</span></code>, <code class="docutils literal notranslate"><span class="pre">__ge__</span></code>, <code class="docutils literal notranslate"><span class="pre">__and__</span></code>, <code class="docutils literal notranslate"><span class="pre">__or__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__sub__</span></code>, <code class="docutils literal notranslate"><span class="pre">__xor__</span></code>, and <code class="docutils literal notranslate"><span class="pre">isdisjoint</span></code></p></td>
</tr>
<tr class="row-odd"><td><p><a class="reference internal" href="#collections.MutableSet" title="collections.MutableSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">MutableSet</span></code></a></p></td>
<td><p><a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a></p></td>
<td><p><code class="docutils literal notranslate"><span class="pre">__contains__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__iter__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__len__</span></code>,
<code class="docutils literal notranslate"><span class="pre">add</span></code>,
<code class="docutils literal notranslate"><span class="pre">discard</span></code></p></td>
<td><p>Inherited <a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a> methods and
<code class="docutils literal notranslate"><span class="pre">clear</span></code>, <code class="docutils literal notranslate"><span class="pre">pop</span></code>, <code class="docutils literal notranslate"><span class="pre">remove</span></code>, <code class="docutils literal notranslate"><span class="pre">__ior__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__iand__</span></code>, <code class="docutils literal notranslate"><span class="pre">__ixor__</span></code>, and <code class="docutils literal notranslate"><span class="pre">__isub__</span></code></p></td>
</tr>
<tr class="row-even"><td><p><a class="reference internal" href="#collections.Mapping" title="collections.Mapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mapping</span></code></a></p></td>
<td><p><a class="reference internal" href="#collections.Sized" title="collections.Sized"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sized</span></code></a>,
<a class="reference internal" href="#collections.Iterable" title="collections.Iterable"><code class="xref py py-class docutils literal notranslate"><span class="pre">Iterable</span></code></a>,
<a class="reference internal" href="#collections.Container" title="collections.Container"><code class="xref py py-class docutils literal notranslate"><span class="pre">Container</span></code></a></p></td>
<td><p><code class="docutils literal notranslate"><span class="pre">__getitem__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__iter__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__len__</span></code></p></td>
<td><p><code class="docutils literal notranslate"><span class="pre">__contains__</span></code>, <code class="docutils literal notranslate"><span class="pre">keys</span></code>, <code class="docutils literal notranslate"><span class="pre">items</span></code>, <code class="docutils literal notranslate"><span class="pre">values</span></code>,
<code class="docutils literal notranslate"><span class="pre">get</span></code>, <code class="docutils literal notranslate"><span class="pre">__eq__</span></code>, and <code class="docutils literal notranslate"><span class="pre">__ne__</span></code></p></td>
</tr>
<tr class="row-odd"><td><p><a class="reference internal" href="#collections.MutableMapping" title="collections.MutableMapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">MutableMapping</span></code></a></p></td>
<td><p><a class="reference internal" href="#collections.Mapping" title="collections.Mapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mapping</span></code></a></p></td>
<td><p><code class="docutils literal notranslate"><span class="pre">__getitem__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__setitem__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__delitem__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__iter__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__len__</span></code></p></td>
<td><p>Inherited <a class="reference internal" href="#collections.Mapping" title="collections.Mapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mapping</span></code></a> methods and
<code class="docutils literal notranslate"><span class="pre">pop</span></code>, <code class="docutils literal notranslate"><span class="pre">popitem</span></code>, <code class="docutils literal notranslate"><span class="pre">clear</span></code>, <code class="docutils literal notranslate"><span class="pre">update</span></code>,
and <code class="docutils literal notranslate"><span class="pre">setdefault</span></code></p></td>
</tr>
<tr class="row-even"><td><p><a class="reference internal" href="#collections.MappingView" title="collections.MappingView"><code class="xref py py-class docutils literal notranslate"><span class="pre">MappingView</span></code></a></p></td>
<td><p><a class="reference internal" href="#collections.Sized" title="collections.Sized"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sized</span></code></a></p></td>
<td></td>
<td><p><code class="docutils literal notranslate"><span class="pre">__len__</span></code></p></td>
</tr>
<tr class="row-odd"><td><p><a class="reference internal" href="#collections.ItemsView" title="collections.ItemsView"><code class="xref py py-class docutils literal notranslate"><span class="pre">ItemsView</span></code></a></p></td>
<td><p><a class="reference internal" href="#collections.MappingView" title="collections.MappingView"><code class="xref py py-class docutils literal notranslate"><span class="pre">MappingView</span></code></a>,
<a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a></p></td>
<td></td>
<td><p><code class="docutils literal notranslate"><span class="pre">__contains__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__iter__</span></code></p></td>
</tr>
<tr class="row-even"><td><p><a class="reference internal" href="#collections.KeysView" title="collections.KeysView"><code class="xref py py-class docutils literal notranslate"><span class="pre">KeysView</span></code></a></p></td>
<td><p><a class="reference internal" href="#collections.MappingView" title="collections.MappingView"><code class="xref py py-class docutils literal notranslate"><span class="pre">MappingView</span></code></a>,
<a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a></p></td>
<td></td>
<td><p><code class="docutils literal notranslate"><span class="pre">__contains__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__iter__</span></code></p></td>
</tr>
<tr class="row-odd"><td><p><a class="reference internal" href="#collections.ValuesView" title="collections.ValuesView"><code class="xref py py-class docutils literal notranslate"><span class="pre">ValuesView</span></code></a></p></td>
<td><p><a class="reference internal" href="#collections.MappingView" title="collections.MappingView"><code class="xref py py-class docutils literal notranslate"><span class="pre">MappingView</span></code></a></p></td>
<td></td>
<td><p><code class="docutils literal notranslate"><span class="pre">__contains__</span></code>, <code class="docutils literal notranslate"><span class="pre">__iter__</span></code></p></td>
</tr>
</tbody>
</table>
<dl class="class">
<dt id="collections.Container">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">Container</code><a class="headerlink" href="#collections.Container" title="Permalink to this definition">¶</a></dt>
<dt id="collections.Hashable">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">Hashable</code><a class="headerlink" href="#collections.Hashable" title="Permalink to this definition">¶</a></dt>
<dt id="collections.Sized">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">Sized</code><a class="headerlink" href="#collections.Sized" title="Permalink to this definition">¶</a></dt>
<dt id="collections.Callable">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">Callable</code><a class="headerlink" href="#collections.Callable" title="Permalink to this definition">¶</a></dt>
<dd><p>ABCs for classes that provide respectively the methods <a class="reference internal" href="../reference/datamodel.html#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a>,
<a class="reference internal" href="../reference/datamodel.html#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a>, and <a class="reference internal" href="../reference/datamodel.html#object.__call__" title="object.__call__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__call__()</span></code></a>.</p>
</dd></dl>

<dl class="class">
<dt id="collections.Iterable">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">Iterable</code><a class="headerlink" href="#collections.Iterable" title="Permalink to this definition">¶</a></dt>
<dd><p>ABC for classes that provide the <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> method.
See also the definition of <a class="reference internal" href="../glossary.html#term-iterable"><span class="xref std std-term">iterable</span></a>.</p>
</dd></dl>

<dl class="class">
<dt id="collections.Iterator">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">Iterator</code><a class="headerlink" href="#collections.Iterator" title="Permalink to this definition">¶</a></dt>
<dd><p>ABC for classes that provide the <a class="reference internal" href="stdtypes.html#iterator.__iter__" title="iterator.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> and
<a class="reference internal" href="stdtypes.html#iterator.next" title="iterator.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> methods.  See also the definition of <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a>.</p>
</dd></dl>

<dl class="class">
<dt id="collections.Sequence">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">Sequence</code><a class="headerlink" href="#collections.Sequence" title="Permalink to this definition">¶</a></dt>
<dt id="collections.MutableSequence">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">MutableSequence</code><a class="headerlink" href="#collections.MutableSequence" title="Permalink to this definition">¶</a></dt>
<dd><p>ABCs for read-only and mutable <a class="reference internal" href="../glossary.html#term-sequence"><span class="xref std std-term">sequences</span></a>.</p>
</dd></dl>

<dl class="class">
<dt id="collections.Set">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">Set</code><a class="headerlink" href="#collections.Set" title="Permalink to this definition">¶</a></dt>
<dt id="collections.MutableSet">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">MutableSet</code><a class="headerlink" href="#collections.MutableSet" title="Permalink to this definition">¶</a></dt>
<dd><p>ABCs for read-only and mutable sets.</p>
</dd></dl>

<dl class="class">
<dt id="collections.Mapping">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">Mapping</code><a class="headerlink" href="#collections.Mapping" title="Permalink to this definition">¶</a></dt>
<dt id="collections.MutableMapping">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">MutableMapping</code><a class="headerlink" href="#collections.MutableMapping" title="Permalink to this definition">¶</a></dt>
<dd><p>ABCs for read-only and mutable <a class="reference internal" href="../glossary.html#term-mapping"><span class="xref std std-term">mappings</span></a>.</p>
</dd></dl>

<dl class="class">
<dt id="collections.MappingView">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">MappingView</code><a class="headerlink" href="#collections.MappingView" title="Permalink to this definition">¶</a></dt>
<dt id="collections.ItemsView">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">ItemsView</code><a class="headerlink" href="#collections.ItemsView" title="Permalink to this definition">¶</a></dt>
<dt id="collections.KeysView">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">KeysView</code><a class="headerlink" href="#collections.KeysView" title="Permalink to this definition">¶</a></dt>
<dt id="collections.ValuesView">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">ValuesView</code><a class="headerlink" href="#collections.ValuesView" title="Permalink to this definition">¶</a></dt>
<dd><p>ABCs for mapping, items, keys, and values <a class="reference internal" href="../glossary.html#term-dictionary-view"><span class="xref std std-term">views</span></a>.</p>
</dd></dl>

<p>These ABCs allow us to ask classes or instances if they provide
particular functionality, for example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">size</span> <span class="o">=</span> <span class="kc">None</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">myvar</span><span class="p">,</span> <span class="n">collections</span><span class="o">.</span><span class="n">Sized</span><span class="p">):</span>
    <span class="n">size</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">myvar</span><span class="p">)</span>
</pre></div>
</div>
<p>Several of the ABCs are also useful as mixins that make it easier to develop
classes supporting container APIs.  For example, to write a class supporting
the full <a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a> API, it only necessary to supply the three underlying
abstract methods: <a class="reference internal" href="../reference/datamodel.html#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a>, and <a class="reference internal" href="../reference/datamodel.html#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a>.
The ABC supplies the remaining methods such as <a class="reference internal" href="../reference/datamodel.html#object.__and__" title="object.__and__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__and__()</span></code></a> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">isdisjoint()</span></code></p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">ListBasedSet</span><span class="p">(</span><span class="n">collections</span><span class="o">.</span><span class="n">Set</span><span class="p">):</span>
     <span class="sd">&#39;&#39;&#39; Alternate set implementation favoring space over speed</span>
<span class="sd">         and not requiring the set elements to be hashable. &#39;&#39;&#39;</span>
     <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">iterable</span><span class="p">):</span>
         <span class="bp">self</span><span class="o">.</span><span class="n">elements</span> <span class="o">=</span> <span class="n">lst</span> <span class="o">=</span> <span class="p">[]</span>
         <span class="k">for</span> <span class="n">value</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">:</span>
             <span class="k">if</span> <span class="n">value</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">lst</span><span class="p">:</span>
                 <span class="n">lst</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>

     <span class="k">def</span> <span class="nf">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
         <span class="k">return</span> <span class="nb">iter</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">elements</span><span class="p">)</span>

     <span class="k">def</span> <span class="nf">__contains__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
         <span class="k">return</span> <span class="n">value</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">elements</span>

     <span class="k">def</span> <span class="nf">__len__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
         <span class="k">return</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">elements</span><span class="p">)</span>

<span class="n">s1</span> <span class="o">=</span> <span class="n">ListBasedSet</span><span class="p">(</span><span class="s1">&#39;abcdef&#39;</span><span class="p">)</span>
<span class="n">s2</span> <span class="o">=</span> <span class="n">ListBasedSet</span><span class="p">(</span><span class="s1">&#39;defghi&#39;</span><span class="p">)</span>
<span class="n">overlap</span> <span class="o">=</span> <span class="n">s1</span> <span class="o">&amp;</span> <span class="n">s2</span>            <span class="c1"># The __and__() method is supported automatically</span>
</pre></div>
</div>
<p>Notes on using <a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a> and <a class="reference internal" href="#collections.MutableSet" title="collections.MutableSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">MutableSet</span></code></a> as a mixin:</p>
<ol class="arabic simple">
<li><p>Since some set operations create new sets, the default mixin methods need
a way to create new instances from an iterable. The class constructor is
assumed to have a signature in the form <code class="docutils literal notranslate"><span class="pre">ClassName(iterable)</span></code>.
That assumption is factored-out to an internal classmethod called
<code class="xref py py-meth docutils literal notranslate"><span class="pre">_from_iterable()</span></code> which calls <code class="docutils literal notranslate"><span class="pre">cls(iterable)</span></code> to produce a new set.
If the <a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a> mixin is being used in a class with a different
constructor signature, you will need to override <code class="xref py py-meth docutils literal notranslate"><span class="pre">_from_iterable()</span></code>
with a classmethod that can construct new instances from
an iterable argument.</p></li>
<li><p>To override the comparisons (presumably for speed, as the
semantics are fixed), redefine <a class="reference internal" href="../reference/datamodel.html#object.__le__" title="object.__le__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__le__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__ge__" title="object.__ge__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__ge__()</span></code></a>,
then the other operations will automatically follow suit.</p></li>
<li><p>The <a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a> mixin provides a <code class="xref py py-meth docutils literal notranslate"><span class="pre">_hash()</span></code> method to compute a hash value
for the set; however, <a class="reference internal" href="../reference/datamodel.html#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> is not defined because not all sets
are hashable or immutable.  To add set hashability using mixins,
inherit from both <a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Set()</span></code></a> and <a class="reference internal" href="#collections.Hashable" title="collections.Hashable"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Hashable()</span></code></a>, then define
<code class="docutils literal notranslate"><span class="pre">__hash__</span> <span class="pre">=</span> <span class="pre">Set._hash</span></code>.</p></li>
</ol>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<ul class="simple">
<li><p><a class="reference external" href="https://code.activestate.com/recipes/576694/">OrderedSet recipe</a> for an
example built on <a class="reference internal" href="#collections.MutableSet" title="collections.MutableSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">MutableSet</span></code></a>.</p></li>
<li><p>For more about ABCs, see the <a class="reference internal" href="abc.html#module-abc" title="abc: Abstract base classes according to PEP 3119."><code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code></a> module and <span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3119"><strong>PEP 3119</strong></a>.</p></li>
</ul>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">8.3. <code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code> — High-performance container datatypes</a><ul>
<li><a class="reference internal" href="#counter-objects">8.3.1. <code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code> objects</a></li>
<li><a class="reference internal" href="#deque-objects">8.3.2. <code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code> objects</a><ul>
<li><a class="reference internal" href="#deque-recipes">8.3.2.1. <code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code> Recipes</a></li>
</ul>
</li>
<li><a class="reference internal" href="#defaultdict-objects">8.3.3. <code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code> objects</a><ul>
<li><a class="reference internal" href="#defaultdict-examples">8.3.3.1. <code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code> Examples</a></li>
</ul>
</li>
<li><a class="reference internal" href="#namedtuple-factory-function-for-tuples-with-named-fields">8.3.4. <code class="xref py py-func docutils literal notranslate"><span class="pre">namedtuple()</span></code> Factory Function for Tuples with Named Fields</a></li>
<li><a class="reference internal" href="#ordereddict-objects">8.3.5. <code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code> objects</a><ul>
<li><a class="reference internal" href="#ordereddict-examples-and-recipes">8.3.5.1. <code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code> Examples and Recipes</a></li>
</ul>
</li>
<li><a class="reference internal" href="#collections-abstract-base-classes">8.3.6. Collections Abstract Base Classes</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="calendar.html"
                        title="previous chapter">8.2. <code class="xref py py-mod docutils literal notranslate"><span class="pre">calendar</span></code> — General calendar-related functions</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="heapq.html"
                        title="next chapter">8.4. <code class="xref py py-mod docutils literal notranslate"><span class="pre">heapq</span></code> — Heap queue algorithm</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/collections.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="heapq.html" title="8.4. heapq — Heap queue algorithm"
             >next</a> |</li>
        <li class="right" >
          <a href="calendar.html" title="8.2. calendar — General calendar-related functions"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.17 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" >8. Data Types</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Oct 19, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.0.1.
    </div>

  </body>
</html>