Most efficient method to get key for similar values in a dict
<p>I have a dictionary of objects:</p>

<pre><code># I have thousands of objects in my real world scenario
dic = {'k1':obj1, 'k2':obj2, 'k3':obj3, ...}
# keys are string
# objs are MyObject
</code></pre>

<p><em>Edit</em>: Sorry for letting doubt in the question. Here is the exact class and the <code>like()</code> function:</p>

<pre><code>class MyObject(object):
    def __init__(self, period, dimensions):
        self.id = None
        self.period = period # period is etree.Element
        self.dimensions = dict() # id -&gt; lxml.XMLElements
        for dim in dimensions:
            # there must be only one child: the typed dimension
            self.dimensions[dim.get('dimension')] = dim[0]
        self._hash = None

    def __eq__(self, other):
        return isinstance(other, MyObject)
            and self.period == other.period
            and self.dimensions == other.dimensions

    def like(self, other):
        return (other is not None \
            and self.period == other.period \
           and self.dimensions.keys() == other.dimensions.keys())
</code></pre>

<p>I wonder how I can have the best implementation for finding objects in dictionary <code>dic</code> that are similar to a given value <code>val</code>. Something equivalent to:</p>

<pre><code>def find_keys(dic, val):
    return [v for v in dic if v.like(val))
</code></pre>

<p>However this method is too slow, because I have thousands of iterations over <code>find-keys()</code> and thousands objects in the dictionary.</p>

<p>Right now, I have implemented a <code>__hash__(self)</code> on these objects, and added the key as a property:</p>

<pre><code>    def __hash__(self):
        if self._hash is None:
            self._hash = hash(self.periodtype) ^ \
                hash(tuple(sorted(self.dimensions.values())))
        return self._hash
</code></pre>

<p>Then, I have built a lookup dictionary that is</p>

<pre><code>hash_dic = { hash(obj1): [obj1], hash(obj2): [obj2, obj3] }
</code></pre>

<p>And this new search method is much faster:</p>

<pre><code>def find_keys_fast(dic, val):
    prefetched=hash_dic[hash(val)]
    return [x.key for x in prefetched if x.like(val)]
</code></pre>

<p>Since <code>__hash__</code> is a native function internally used by Sets and Dictionaries, is there anything faster or more elegant I could do?</p>
