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>The most straightforward way is to iterate over both the containers and check:</p>

<pre><code>for key in mylist:
    if not any(key in dic for dic in mydictlist):
        print key, "missing"
</code></pre>

<p>However, if you have a lot of keys and/or dictionaries, this is not going to be efficient: it iterates over <code>mydictlist</code> once for each element in <code>mylist</code>, which is O(n*m). Instead, consider a set operation:</p>

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

python