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

13,199

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.

Share:
13,199
Zero0Ho
Author by

Zero0Ho

Updated on June 25, 2022

Comments

  • Zero0Ho
    Zero0Ho almost 2 years

    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?

  • Zero0Ho
    Zero0Ho over 8 years
    Oh! It's work now. and I have more question I try this before choices = sorted(choices.items(), key=itemgetter(1)) but it didn't work
  • Martijn Pieters
    Martijn Pieters over 8 years
    @ZeroOHo: that's because choices is a list of dictionaries. Lists don't have a .items() method.