Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I tried to sort a list, I got an error 'dict' object has no attribute

My code which created the list is:

choices = []
for bet in Bet.objects.all():
    #...
    #Here is code that skip loop if bet.choice exist in choices[]
    #...
    temp = {
        'choice':bet.choice,
        'amount':bet.sum,
        'count':bets.filter(choice=bet.choice).count()}
    choices.append(temp)

choices.sort(key=attrgetter('choice'), reverse=True)
choices.sort(key=attrgetter('amount'), reverse=True)
choices.sort(key=attrgetter('count'), reverse=True)

I have to sort by list because model orderby() cant sort by count(),can it?

like image 426
Zero0Ho Avatar asked Dec 02 '15 12:12

Zero0Ho


1 Answers

Your dictionaries have no choice, amount or count attributes. Those are keys, so you need to use an itemgetter() object instead.

from operator import itemgetter

choices.sort(key=itemgetter('choice'), reverse=True)
choices.sort(key=itemgetter('amount'), reverse=True)
choices.sort(key=itemhetter('count'), reverse=True)

If you want to sort by multiple criteria, just sort once, with the criteria named in order:

choices.sort(key=itemgetter('count', 'amount', 'choice'), reverse=True)

You probably want to have the database do the sorting, however.

like image 59
Martijn Pieters Avatar answered Nov 14 '22 21:11

Martijn Pieters