按两个不同的键对dict列表进行排序

2024-10-04 09:32:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试解析一个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'}]

Tags: csvin排序顺序themerowsquotechapter
1条回答
网友
1楼 · 发布于 2024-10-04 09:32:23

如果你换了这条线

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

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

会有用的。你知道吗

相关问题 更多 >