Dictionary Views in Python
<p>In <a class="wikilink" href="/python/">Python</a>, <a class="wikilink" href="/dictionary/">dictionary</a> views actually change their data if the underlying dictionary changes. Let's remove some keys:</p>
<pre class="codehilite"><code class="language-pycon">>>> data = {'a': 1, 'b': 2, 'c': 3}
>>> keys = data.keys()
>>> keys
dict_keys(['a', 'b', 'c'])
>>> del data['a']
>>> keys
dict_keys(['b', 'c'])
>>>
</code></pre>
<p>It also works for the items:</p>
<pre class="codehilite"><code class="language-pycon">>>> items = data.items()
>>> items
dict_items([('b', 2), ('c', 4)])
>>> items_list = list(items)
>>> items_list
[('b', 2), ('c', 4)]
>>> data['c'] = 0
>>> items
dict_items([('b', 2), ('c', 0)])
>>> items_list
[('b', 2), ('c', 4)]
</code></pre>
<p>Note that once the <code>dict_items</code> object is cast into a list, it loses the reference to the data item. </p>
<p>And, just out of curiosity and, as expected, it is not serializable:</p>
<pre class="codehilite"><code class="language-pycon">>>> with open('test.dat', 'w') as f:
... pickle.dump(items, f)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: cannot pickle 'dict_items' object
</code></pre>
Backlinks
These are the other notes that link to this one.
Nothing links here, how did you reach this page then?
Comment
Share your thoughts on this note. Comments are not public, they are
messages sent directly to my inbox.