Python Query list for oldest date
<p>My query returns the following in a list:</p>

<pre><code>"Alex";"275467125";"2015-02-03 02:55:36-05";"1"
"Alex";"275467125";"2015-01-13 02:09:39-05";"1"
"Alex";"275467125";"2015-01-05 04:13:35-05";"1"
"Alex";"275467125";"2014-12-27 04:55:47-05";"1"
"Alex";"275467125";"2014-12-27 04:54:52-05";"1"
"Alex";"275467125";"2014-12-07 03:13:24-05";"1"
"Alex";"275467125";"2014-12-04 03:34:56-05";"1"
"Alex";"275467125";"2014-12-02 04:16:33-05";"1"
"Ali";"275464747";"2016-02-17 10:52:12-05";"2"
"Alladin";"275467455";"2016-03-13 06:51:52-04";"2"
"Alladin";"275467455";"2016-03-13 06:51:47-04";"2"
"Anna";"275467401";"2016-03-26 03:56:41-04";"1"
"Anna";"275467401";"2016-03-26 03:55:21-04";"1"
"Anna";"275467401";"2016-03-21 23:04:28-04";"1"
"Anna";"275467401";"2016-02-12 13:24:44-05";"1"
"Anna";"275467401";"2015-12-03 08:20:35-05";"1"
"Anna";"275467401";"2015-11-09 04:18:27-05";"1"
"Anna";"275467401";"2015-11-09 04:11:59-05";"1"
"Anna";"275467401";"2015-09-13 21:27:12-04";"1"
</code></pre>

<p>I want to create a dictionary of person's name with the oldest record they have. I've figured out:</p>

<pre><code>oldestlist = {d[0]:d[2] for d in records}
</code></pre>

<p>This returns a correct answer but my worry is that if I am presented a list that is not formatted in a descending order of date/time it will not provide the correct answer. What is the best way to create a dictionary with a name and the oldest date?</p>

<p>Since you need last record for each <code>name</code> instead of doing it explicitly with the <code>dict</code> make your queryset to perform <code>GROUP BY</code> on name. In Django you can do that using <code>.annotate</code> as is mentioned here: <a href="http://stackoverflow.com/questions/19923877/django-orm-get-latest-for-each-group">Django Orm get latest for each group</a></p>

<p>Hence, your querset should be like:</p>

<pre><code>YourModel.objects.values('name_column').annotate(latest_date=Max('date'))
</code></pre>

<hr>

<p><em>Additional piece of information</em>, you should be using <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#django.db.models.query.QuerySet.order_by" rel="nofollow"><code>order_by(-your_date_column)</code></a> with your queryset in order to ensure data is always returned in desc order where <code>-</code> ensure desc order when list is needed. </p>

python list date dictionary time