簡體   English   中英

用兩個不同的鍵對字典列表進行排序

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM