通过两个不同的键对dicts列表进行排序

时间:2013-10-23 18:05:18

标签: python sorting csv

我正在尝试解析csv文件,并希望通过升序章节对输出进行排序,然后按主题键排序 - 同时保持章节顺序。

我已设法对下面的章节进行排序,但无法按主题排序,同时保留章节顺序。

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'}]

1 个答案:

答案 0 :(得分:1)

如果更改此行

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

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

它会起作用。