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>Try this,<code>all</code> will check the existence of <code>dictA</code> in <code>listA</code>.</p>

<pre><code>[i for i in listA if all(j in i.items() for j in dictA.items())]
</code></pre>

<p><strong>Result</strong> </p>

<pre><code>[{'c1': 4, 'gtm': 3, 'id': '111', 't': 1, 'tid': 2},
 {'c1': 4, 'c2': 5, 'gtm': 3, 'id': '333', 't': 1, 'tid': 2}]
</code></pre>

python dictionary