puffin
puffin

Reputation: 1351

Sorting a list of dicts by two different keys

I'm trying to parse a csv file and would like to sort the output by ascending chapters, then sort - while maintaining the chapter order - by the theme key.

I have managed to sort the chapters below, but unable to sort by theme while preserving chapter order.

In [35]: d = DictReader(open('gatsby-test.csv', 'rb'))

In [36]: rows = []

In [37]: for row in d:
   ....:     rows.append(row)
   ....:     

In [38]: sorted_d = sorted(rows, key=lambda item: item['chapter'])

In [39]: sorted_d
Out[39]: 
[{'chapter': 'Chapter 1',
  'character': 'Nick Carraway',
  'explanation': 'explanation one',
  'quote': '"quote one"',
  'theme': 'love'},
 {'chapter': 'Chapter 2',
  'character': 'Daisy Buchanan',
  'explanation': 'explanation two',
  'quote': '"quote two"',
  'theme': 'wealth'},
 {'chapter': 'Chapter 2',
  'character': 'Jordan Baker',
  'explanation': 'explanation five',
  'quote': '"quote five"',
  'theme': 'dissatisfaction'},
 {'chapter': 'Chapter 3',
  'character': 'Daisy Buchanan',
  'explanation': 'explanation four',
  'quote': '"quote four"',
  'theme': 'isolation'},
 {'chapter': 'Chapter 3',
  'character': 'Daisy Buchanan',
  'explanation': 'explanation three',
  'quote': '"quote three"',
  'theme': 'isolation'}]

Upvotes: 1

Views: 76

Answers (1)

Hoopdady
Hoopdady

Reputation: 2356

If you change this line

sorted_d = sorted(rows, key=lambda item: item['chapter'])

to

sorted_d = sorted(rows, key=lambda item: (item['chapter'], item['theme']))

it will work.

Upvotes: 1

Related Questions