[英]Sorting a list of dicts by two different keys
我正在尝试解析一个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'}]
如果您更改此行
sorted_d = sorted(rows, key=lambda item: item['chapter'])
至
sorted_d = sorted(rows, key=lambda item: (item['chapter'], item['theme']))
它会工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.