Get intersection of list elements with different sublist datatypes
<p>I have two lists, which contains list elements, e.g:</p>

<pre><code>list1 = [['placeholder1', {'data': 'data1'}], ['placeholder2', {'data': 'data2'}], ['placeholder2', {'data': 'data1'}]]
list2 = [['placeholder2', {'data': 'data2'}], ['placeholder3', {'data': 'data5'}]]

intersection_result = [['placeholder2', {'data': 'data2'}]]
</code></pre>

<p>The structure of the sub-list elements is just an example. It can also happen that all the sub-list elements contains strings <code>['asdf', 'qwert']</code> or a mixture of string and numbers <code>['sdfs', 232]</code>. However, the sub-list structure is always the same (in both lists).</p>

<p>How can I get the intersection of lists elements which are identical in both lists?</p>

<p>A simple solution, which would be <strong>independent of the structure of your data</strong>.
You can generate <a href="http://stackoverflow.com/questions/16735786/how-to-generate-unique-equal-hash-for-equal-dictionaries">signature hashes</a> (using json or pformat) for your data, and find common hashes in both list1 and list2.</p>

<p><strong>Demo</strong> : <a href="http://ideone.com/5i9cs8" rel="nofollow">http://ideone.com/5i9cs8</a> </p>

<pre><code>import json

list1 = [['placeholder1', {'data': 'data1'}], ['placeholder2', {'data': 'data2'}], ['placeholder2', {'data': 'data1'}]]
list2 = [['placeholder2', {'data': 'data2'}], ['placeholder3', {'data': 'data5'}]]
sig1 = { hash(json.dumps(x, sort_keys=True)):x for x in list1 }
sig2 = { hash(json.dumps(x, sort_keys=True)):x for x in list2 }
result = {x:sig1[x] for x in sig1 if x in sig2}
print(result)
#prints {-7754841686355067234: ['placeholder2', {'data': 'data2'}]}
</code></pre>

<ul>
<li>If your dictionaries have data which does not support json serialization e.g. datetime, pformat will work well, or you can use cPickle, <code>str</code> will also work for simple cases. You can make the choice based on your dataset and efficiency required.</li>
</ul>

python list python-3.x intersection python-3.5