Create a new list from two dictionaries
<p>This is a question about Python. I have the following list of dictionaries:</p>

<pre><code>listA = [
          {"t": 1, "tid": 2, "gtm": 3, "c1": 4, "id": "111"},
          {"t": 3, "tid": 4, "gtm": 3, "c1": 4, "c2": 5, "id": "222"},
          {"t": 1, "tid": 2, "gtm": 3, "c1": 4, "c2": 5, "id": "333"},
          {"t": 5, "tid": 6, "gtm": 3, "c1": 4, "c2": 5, "id": "444"}
        ]
</code></pre>

<p>and a dictionary I wanted to compare with:</p>

<pre><code>dictA = {"t": 1, "tid": 2, "gtm": 3}
</code></pre>

<p>I wanted to create a list of dicts that match all the items in <strong>dictA</strong> from <strong>listA</strong> and to include the "id" field as well:</p>

<pre><code>listB = [
          {"t": 1, "tid": 2, "gtm": 3, "id": "111"},
          {"t": 1, "tid": 2, "gtm": 3, "id": "333"}
        ]
</code></pre>

<p>I tried doing this:</p>

<pre><code>for k in listA:
    for key, value in k.viewitems() &amp; dictA.viewitems():
        print key, value
</code></pre>

<p>But it's matching any item in <strong>dictA</strong>.</p>

<p>You would need to check the <em>length</em> of the intersection, just checking <code>if dct.viewitems() &amp; dictA.viewitems()</code> would evaluate to True for any intersection :</p>

<pre><code>[dct for dct in listA if len(dct.viewitems() &amp; dictA.viewitems()) == len(dictA)]
</code></pre>

<p>Or just check for a subset, if the items from dictA are a <a href="https://docs.python.org/2/library/sets.html#set-objects" rel="nofollow">subset</a> of each dict:</p>

<pre><code>[dct for dct in listA if dictA.viewitems() &lt;= dct.viewitems()]
</code></pre>

<p>Or reverse the logic looking for a  <a href="https://docs.python.org/2/library/sets.html#set-objects" rel="nofollow">superset</a>:</p>

<pre><code> [dct for dct in listA if dct.viewitems() &gt;= dictA.viewitems()]
</code></pre>

python dictionary