Example of a python dictionary multiconditional sort method

  • 2020-04-02 13:49:24
  • OfStack

Sorting dictionaries is a common occurrence during project writing, and it only takes a few lines of code to implement multi-conditional sorting. This fully demonstrates the benefits of python.


teamitems = [{'team':'France'     , 'P':1 , 'GD':-3 , 'GS':1 , 'GA':4},
            {'team':'Uruguay'     , 'P':7 , 'GD':4  , 'GS':4 , 'GA':0},
            {'team':'SouthAfrica' , 'P':4 , 'GD':-2 , 'GS':3 , 'GA':5},
            {'team':'Mexico'      , 'P':4 , 'GD':1  , 'GS':3 , 'GA':2}] print sorted(teamitems ,key = lambda x:(x['P'],x['GD'],x['GS'],x['GA']),reverse=True)

The above code is sorted by 'P',' GD',' GS','GA', and reverse=True means descending order

Of course not bad


from operator import itemgetter
print sorted(teamitems ,key = itemgetter('P','GD','GS','GA'),reverse=True)


Related articles: