Ensure list of dicts has a dict with key for each key in list
<p>Context:
I'm using an Ajax call to return some complex JSON from a python module. I have to use a list of keys and confirm that a list of single-item dicts contains a dict with each key.</p>

<p>Example:</p>

<pre><code>mylist=['this', 'that', 'these', 'those']

mydictlist=[{'this':1},{'that':2},{'these':3}]
</code></pre>

<p>How do I know that mydictlist is missing the "those" key? Once I know that, I can append {'those':4} to mylist. Simply checking for "those" won't work since the list is dynamic. The data structure cannot change.</p>

<p>Thanks.</p>

<p>Simple code is to convert your search list to a set, then use differencing to determine what you're missing:</p>

<pre><code>missing = set(mylist).difference(*mydictlist)
</code></pre>

<p>which gets you <code>missing</code> of <code>{'those'}</code>.</p>

<p>Since the named <code>set</code> methods can take multiple arguments (and they need not be <code>set</code>s themselves), you can just unpack all the <code>dict</code>s as arguments to <code>difference</code> to subtract all of them from your <code>set</code> of desired keys at once.</p>

<p>If you do need to handle duplicates (to make sure you see each of the <code>keys</code> in <code>mylist</code> at least that many time in <code>mydictlist</code>'s keys, so <code>mylist</code> might contain a value twice which must occur twice in the <code>dict</code>s), you can use <code>collections</code> and <code>itertools</code> to get remaining counts:</p>

<pre><code>from collections import Counter
from itertools import chain

c = Counter(mylist)
c.subtract(chain.from_iterable(mydictlist))
# In 3.3+, easiest way to remove 0/negative counts
c = +c

# In pre-3.3 Python, change c = +c to get the same effect slightly less efficiently
c += Counter()
</code></pre>

python