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>For python 2.7 :  </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 all(x in k.viewitems() for x in dictA.viewitems()):
        print k
</code></pre>

<p>It gives output as :</p>

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

<p>And if you want to create list then instead of <code>print</code>, add dictionary to list As follows:</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}
ans =[]
for k in listA:
    if all(x in k.viewitems() for x in dictA.viewitems()):
        ans.append(k)
        #print k
print ans
</code></pre>

<p>It gives output:</p>

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

python dictionary