Python中如何对值为列表的字典按指定值进行排序
实现方案
Python 3.7及以上版本默认支持字典保留插入顺序,直接调用sorted()方法处理字典的键值对即可实现需求。
示例代码
# 定义原始字典 original_dict = {'Sun': ['Sole', 3], 'Moon': ['Luna', 0], 'Mercury': ['Mercurio', 0], 'Venus': ['Venere', 16]} # 按值列表的第二个元素降序排序 sorted_dict = dict(sorted(original_dict.items(), key=lambda item: item[1][1], reverse=True)) # 输出验证 print(sorted_dict)
输出结果
{'Venus': ['Venere', 16], 'Sun': ['Sole', 3], 'Moon': ['Luna', 0], 'Mercury': ['Mercurio', 0]}
逻辑说明
original_dict.items()会返回字典所有键值对的可迭代对象,每个元素为(键, 值)格式的元组key=lambda item: item[1][1]指定排序规则为取每个值列表索引为1的数值作为排序依据reverse=True指定按降序排列,数值越大排序越靠前- 最后用
dict()将排序后的元组列表转换为字典即可得到目标结果
低版本兼容方案
如果使用Python 3.6及更早版本,字典本身不保留插入顺序,需要使用collections.OrderedDict存储排序结果:
from collections import OrderedDict original_dict = {'Sun': ['Sole', 3], 'Moon': ['Luna', 0], 'Mercury': ['Mercurio', 0], 'Venus': ['Venere', 16]} sorted_dict = OrderedDict(sorted(original_dict.items(), key=lambda item: item[1][1], reverse=True))
内容的提问来源于stack exchange,提问作者Roberto Mento
相关产品推荐
相关产品推荐

