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 can use a <a href="https://docs.python.org/2/library/stdtypes.html#dictionary-view-objects" rel="nofollow">dictionary view</a>:</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"}
        ]

dictA = {"t": 1, "tid": 2, "gtm": 3}

for k in listA:
    if dictA.viewitems() &lt;= k.viewitems():
        print k
</code></pre>

<p>And for python 3 use:</p>

<pre><code>if dictA.items() &lt;= k.items():
    print(k)
</code></pre>

python dictionary