Difference between tables
<p>I have two list of dictionaries representing the rows of two tables, so:</p>

<pre><code>tableA = [{"id": 1, "name": "foo"}, {"id": 2, "name": "bar"}]

tableB = [{"id": 1, "name": "bar"}, {"id": 3, "name": "baz"}]
</code></pre>

<p>I want to obtain the difference in the following way:</p>

<pre><code>added = [{"id": 3, "name": "baz"}]

updated = [{"id": 1, "name": "bar"}]
</code></pre>

<p>I know, that <code>id</code> is unique.</p>

<p>So, I am planning to loop over <code>tableB</code>, ask for the <code>id</code>, if they are equal then compare the dicts to know if it is <code>updated</code>, if not the id is new and it is <code>added</code>.</p>

<pre><code>for x in tableA:
    idexists = false
    for y in tableY:
        if x["id"] == y["id"]:
           if x != y:
              updated.append(x)
           idexists = true
    if not idexists:
        added.append(x)
</code></pre>

<p>Is it correct? Can it be done in pythonic way?</p>

<p>I would <em>restructure</em> the tables into a more conveninent form of <code>id</code>: <code>name</code> dictionaries and then <a href="http://stackoverflow.com/q/1165352/771848">diff</a>:</p>

<pre><code>from deepdiff import DeepDiff


tableA = [{"id": 1, "name": "foo"}, {"id": 2, "name": "bar"}]

tableB = [{"id": 1, "name": "bar"}, {"id": 3, "name": "baz"}]

tableA = {item["id"]: item["name"] for item in tableA}
tableB = {item["id"]: item["name"] for item in tableB}

print(DeepDiff(tableA, tableB))
</code></pre>

<p>Prints:</p>

<pre><code>{
  'dictionary_item_added': {'root[3]'}, 
  'dictionary_item_removed': {'root[2]'}, 
  'values_changed': {
    'root[1]': { 
      'old_value': 'foo', 
      'new_value': 'bar'
    }
  }
}
</code></pre>

<p>For calculating the differences used <code>deepDiff</code> module suggested <a href="http://stackoverflow.com/a/26079022/771848">here</a>, but you can use any of the suggested solutions from the linked thread.</p>

<hr>

<p>Another idea could be to transform the list of dictionaries into a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow"><code>pandas.DataFrame</code></a> and then diff:</p>

<ul>
<li><a href="http://stackoverflow.com/questions/17095101/outputting-difference-in-two-pandas-dataframes-side-by-side-highlighting-the-d">Outputting difference in two pandas dataframes side by side - highlighting the difference</a></li>
<li><a href="http://stackoverflow.com/questions/20648346/computing-diffs-within-groups-of-a-dataframe">Computing diffs within groups of a dataframe</a></li>
</ul>

python algorithm list dictionary set