【问题标题】:Sorting a list of dicts by two different keys按两个不同的键对字典列表进行排序
【发布时间】:2013-11-02 04:04:58
【问题描述】:

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

【问题讨论】:

    标签: python sorting csv


    【解决方案1】:

    如果你改变这一行

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

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

    它会起作用的。

    【讨论】:

    • 像魅力一样工作!谢谢。
    猜你喜欢
    • 2020-10-04
    • 2014-02-11
    • 1970-01-01
    • 2013-09-16
    • 2019-12-30
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 2019-12-02
    相关资源
    最近更新 更多