如果输入为= {“ i”:4,“ m”:1,“ s”:4,“ p”:2} 输出应为= {“ i”:4,“ s”:4,“ p”:2,“ m”:1} 我如何按降序对字典中的值进行排序
print(sorted(dict,reverse = True))。我用过但没有得到结果
答案 0 :(得分:1)
我现在无法测试此代码,但应该相当接近
# 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}