【发布时间】:2011-02-22 02:43:56
【问题描述】:
我有一个字典列表:
[{'title':'New York Times', 'title_url':'New_York_Times','id':4},
{'title':'USA Today','title_url':'USA_Today','id':6},
{'title':'Apple News','title_url':'Apple_News','id':2}]
我想按标题排序,所以带 A 的元素排在 Z 之前:
[{'title':'Apple News','title_url':'Apple_News','id':2},
{'title':'New York Times', 'title_url':'New_York_Times','id':4},
{'title':'USA Today','title_url':'USA_Today','id':6}]
最好的方法是什么? 另外,有没有办法确保每个字典键的顺序保持不变,例如,总是 title、title_url,然后是 id?
【问题讨论】:
-
请问为什么需要排序的字典?通常,无论如何您都是通过键访问字典,因此顺序无关紧要。
-
呃,这是一个字典 Felix 的列表。
-
@Amber:是的,我明白了……但无论如何,他的第二个问题是针对这个的 ;)
标签: python sorting dictionary