Distinct rows from a list of dictionaries based on values
<p>I have this sample input below <strong>sampleInputDbData</strong></p>

<pre><code>def sampleInputDbData( self ):
    return \
    [
        {'FundCode': 300, 'FundName': 'First Fund', 'ProdStartDate': dt(2016,7,3,4,5,6), 'ProdEndDate': dt(2016,8,3,4,5,6), 'FundFee': 100},
        {'FundCode': 300, 'FundName': 'First Fund', 'ProdStartDate': dt(2016,8,3,4,5,6), 'ProdEndDate': dt(2016,8,3,6,5,6), 'FundFee': 101 },
        {'FundCode': 300, 'FundName': 'First Fund', 'ProdStartDate': dt(2016,8,3,6,5,6), 'ProdEndDate': dt(2016,8,15,6,5,6), 'FundFee': 102 },
        {'FundCode': 301, 'FundName': 'Second Fund', 'ProdStartDate': dt(2016,7,3,4,5,6), 'ProdEndDate': dt(2016,8,3,6,5,6), 'FundFee': 110},
        {'FundCode': 301, 'FundName': 'Second Fund', 'ProdStartDate': dt(2016,8,3,6,5,6), 'ProdEndDate':  dt(2016,8,15,6,5,6), 'FundFee': 111},
        {'FundCode': 302, 'FundName': 'Third Fund', 'ProdStartDate': dt(2016,8,3,6,5,6), 'ProdEndDate':  dt(2016,8,15,6,5,6), 'FundFee': 120},
    ]
</code></pre>

<p>What I want is this <strong>sampleOutputDbData</strong> as output</p>

<pre><code>def sampleOutputDbData( self ):
    return \
    [
        {'FundCode': 300, 'FundName': 'First Fund', 'ProdStartDate': dt(2016,8,3,6,5,6), 'ProdEndDate': dt(2016,8,15,6,5,6), 'FundFee': 102 },
        {'FundCode': 301, 'FundName': 'Second Fund', 'ProdStartDate': dt(2016,8,3,6,5,6), 'ProdEndDate':  dt(2016,8,15,6,5,6), 'FundFee': 111},
        {'FundCode': 302, 'FundName': 'Third Fund', 'ProdStartDate': dt(2016,8,3,6,5,6), 'ProdEndDate':  dt(2016,8,15,6,5,6), 'FundFee': 120},
    ]
</code></pre>

<p>The decision factor is basically: Get all unique <strong>FundCode</strong> based on max value of the key <strong>ProdEndDate</strong>. dt is type datetime</p>

<p>This works:</p>

<pre><code>from collections import defaultdict
from operator import itemgetter

code_dict = defaultdict(list)
for d in sampleInputDbData:
    code_dict[d["FundCode"]].append(d)

output_data = [max(d, key=itemgetter("ProdEndDate")) for d in code_dict.values()]
</code></pre>

<p>I first create a default dict for temporary sorting by <code>FundCode</code>. Each key will contain a list with all dicts with the same <code>FundCode</code>. Then, I'm taking the last <code>ProdEndDate</code> from each list.</p>

python