python class behaves like dictionary-or-list-data-like
<p>In python3 console, input those:</p>

<pre><code>&gt;&gt;&gt; import sys
&gt;&gt;&gt; sys.version_info
sys.version_info(major=3, minor=4, micro=3, releaselevel='final', serial=0)
&gt;&gt;&gt; type(sys.version_info)  # this is class type
&lt;class 'sys.version_info'&gt;
&gt;&gt;&gt; sys.version_info[0:2]  # ?? But it acts like a list-data-like
(3, 4)
</code></pre>

<p>My questions are:</p>

<ol>
<li>How can a class act like dictionary-or-list-data-like? </li>
<li>May give an example to construct a class like this? </li>
<li>Is there some documentation about
this?</li>
</ol>

<p>Python contains several methods for <a href="https://docs.python.org/3/reference/datamodel.html#emulating-container-types" rel="nofollow">emulating container types</a> such as dictionaries and lists. </p>

<p>In particular, consider the following class:</p>

<pre><code> class MyDict(object):
     def __getitem__(self, key):
          # Called for getting obj[key]

     def __setitem__(self, key, value):
          # Called for setting obj[key] = value
</code></pre>

<p>If you write</p>

<pre><code>obj = MyDict()
</code></pre>

<p>Then</p>

<pre><code>obj[3]
</code></pre>

<p>will call the first method, and</p>

<pre><code>obj[3] = 'foo'
</code></pre>

<p>will call the second method.</p>

<p>If you further want to support </p>

<pre><code>len(obj)
</code></pre>

<p>then you just need to add the method</p>

<pre><code>def __len__(self):
    # Return here the logical length
</code></pre>

<hr>

<p>Here is an example of a (very inefficient) dictionary implemented by a list</p>

<pre><code>class MyDict(object):
    def __init__(self, seq=None):
        self._vals = list(seq) if seq is not None else []

    def __getitem__(self, key):
        return [v[1] for v in self._vals if v[0] == key][0]

    def __setitem__(self, key, val):
        self._vals = [v for v in self._vals if v[0] != key]
        self._vals.append((key, val))

    def __len__(self):
        return len(self._vals)
</code></pre>

<p>You can use it pretty much like a regular <code>dict</code>:</p>

<pre><code>obj = MyDict()
obj[2] = 'b'
&gt;&gt;&gt; obj[2]
'b'
</code></pre>

python list class dictionary