Popular recipes tagged "dictionary" and "class"http://code.activestate.com/recipes/tags/dictionary+class/2015-09-29T16:28:46-07:00ActiveState Code RecipesPython add/set attributes to list (Python)
2015-09-29T16:28:46-07:00webby1111http://code.activestate.com/recipes/users/4192908/http://code.activestate.com/recipes/579103-python-addset-attributes-to-list/
<p style="color: grey">
Python
recipe 579103
by <a href="/recipes/users/4192908/">webby1111</a>
(<a href="/recipes/tags/attributes/">attributes</a>, <a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/dictionary/">dictionary</a>, <a href="/recipes/tags/list/">list</a>, <a href="/recipes/tags/subclass/">subclass</a>).
Revision 3.
</p>
<h4 id="python-attribute-listhttpsgithubcomwebby1111python-attribute-list"><a href="https://github.com/webby1111/Python-Attribute-List">Python Attribute List</a></h4>
<p>Add/set attributes to python lists.</p>
<p>A google search for "add attributes to python lists" yields no good stackoverflow answer,
hence the need for this.</p>
<p>Useful for machine learning stuff where you need labeled feature vectors. </p>
<p>This technique can be easily adapted for other built-ins (e.g. int).</p>
<h5 id="the-problem">The Problem</h5>
<pre class="prettyprint"><code>a = [1, 2, 4, 8]
a.x = "Hey!" # AttributeError: 'list' object has no attribute 'x'
</code></pre>
<h5 id="the-solution">The Solution</h5>
<pre class="prettyprint"><code>a = L(1, 2, 4, 8)
a.x = "Hey!"
print a # [1, 2, 4, 8]
print a.x # "Hey!"
print len(a) # 4
# You can also do these:
a = L( 1, 2, 4, 8 , x="Hey!" ) # [1, 2, 4, 8]
a = L( 1, 2, 4, 8 )( x="Hey!" ) # [1, 2, 4, 8]
a = L( [1, 2, 4, 8] , x="Hey!" ) # [1, 2, 4, 8]
a = L( {1, 2, 4, 8} , x="Hey!" ) # [1, 2, 4, 8]
a = L( [2 ** b for b in range(4)] , x="Hey!" ) # [1, 2, 4, 8]
a = L( (2 ** b for b in range(4)) , x="Hey!" ) # [1, 2, 4, 8]
a = L( 2 ** b for b in range(4) )( x="Hey!" ) # [1, 2, 4, 8]
a = L( 2 ) # [2]
</code></pre>
DoubleDict (Python)
2012-07-24T21:24:14-07:00Stephen Chappellhttp://code.activestate.com/recipes/users/2608421/http://code.activestate.com/recipes/578224-doubledict/
<p style="color: grey">
Python
recipe 578224
by <a href="/recipes/users/2608421/">Stephen Chappell</a>
(<a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/dictionary/">dictionary</a>).
</p>
<p>After seeing requests for being able to access keys in a dictionary by value, the following recipe was born. It creates the <code>DoubleDict</code> class and allows just that. To ensure that only one key is returned when accessing it by value, values must be unique just as keys are unique, and this rule is automatically enforced. Most dictionary methods are supported, and many more are added to allow working with the dictionary from the view of the values instead of the keys. Several optional metaclasses are also provided to enable optional features in the <code>DoubleDict</code> class such as data consistency checks and atomic method execution.</p>