假设我们有一个基本模型。

class Log(models.Model):
    key = fields.BigInteger()
    calldate = fields.DateTimeField()
    followupdate = fields.DateTimeField()


可以为同一密钥设置多个followupdates。我想做的是列出列表中最近(按通话日期)计划的后续活动。

在我看来,我有以下几点:

# views.py

def callbacks(request):
    """ get objects where a followupdate has been specified """
    q = Log.objects.filter(followupdate__isnull = False).order_by("-calldate")

    """ deduplicate key so only most recently scheduled followupdate show """
    newresults = []
    seen_key = []
    for result in q:
        if result.key not in seen_key:
            seen_key.append(result.key)
            newresults.append(result)

    results = newresults
    """ What I want to do is equivalent to results.order_by("followupdate") """
    """ But since it's a dictionary now and not a queryset, I can't """
    return render_to_response('callbacks.html', {"callbacks":results})


我需要帮助的是通过键results对字典followupdate重新排序。每本词典中都有一个像这样的键:'followupdate': datetime.date(2013, 3, 25)这是我需要重新排序的依据。

最佳答案

.sort()似乎像这样工作-

l.sort(key=lambda item:item['followupdate'], reverse=True)


测试用例 -

>>> l = [{'followupdate': datetime.date(2013, 3, 25)}, {'followupdate': datetime.date(2013, 3, 24)}, {'followupdate': datetime.date(2013, 3, 29)}]
>>> l
[{'followupdate': datetime.date(2013, 3, 25)}, {'followupdate': datetime.date(2013, 3, 24)}, {'followupdate': datetime.date(2013, 3, 29)}]
>>> l.sort(key=lambda item:item['followupdate'], reverse=True)
>>> l
[{'followupdate': datetime.date(2013, 3, 29)}, {'followupdate': datetime.date(2013, 3, 25)}, {'followupdate': datetime.date(2013, 3, 24)}]

关于python - 重复数据删除和重新排序字典,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15622821/

10-16 02:47