python - 按字典值对字典列表进行排序

标签 python sorting dictionary

我有一个字典列表:

[{'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?

最佳答案

l.sort(key=lambda x:x['title'])

使用多个键进行排序,假设全部按升序排列:

l.sort(key=lambda x:(x['title'], x['title_url'], x['id']))

关于python - 按字典值对字典列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2878084/

相关文章:

python - 从字典创建 DataFrame,其中字典的值为 numpy 数组

python - 使用输入通过 pymysql 插入数据

python - xmlsec 的构建轮失败 - mac

performance - 在 dart 中使用对象作为映射键会对性能产生重大影响吗?

c++ - Visual Studio 2010 x64 中 map 的运行时错误

string - 什么是字典顺序?

python - 在 TensorFlow 中对 5-D 张量进行上采样

python - 类型错误 : executor() takes no arguments (1 given)

c - 使用 Qsort 对 C 程序中的地址进行排序

java - 这是什么算法?