首页 > 解决方案 > 在python中对字典中的值进行排序

问题描述

如果输入为={"i":4,"m":1,"s":4,"p":2} 输出应为={"i":4,"s":4,"p": 2,"m":1} 我如何按降序对字典中的值进行排序

print(sorted(dict,reverse=True))。我用过这个但没有得到结果

标签: pythondictionary

解决方案


我现在无法测试这段代码,但它应该相当接近

# get sorted entries
s = sorted(d.items(), key=lambda e: e[1], reverse=True)
# since Python 3.6, dictionaries are sorted by entry
# if you're using an older Python, check out collections.OrderedDict
d = {k: v for (k,v) in s}

推荐阅读