• 技术文章 >常见问题 >Python常见问题

    python中字典如何按照value排序?

    宋雪维宋雪维2021-02-05 08:47:43原创19011

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    方法一:key使用lambda匿名函数取value进行排序

    dict= {'a':1,'b':4,'c':2}
    sorted(dict.items(),key = lambda x:x[1],reverse = True)

    方法二:使用operator的itemgetter进行排序

    test_data_6=sorted(dict_data.items(),key=operator.itemgetter(1))
    test_data_7=sorted(dict_data.items(),key=operator.itemgetter(1),reverse=True)
    print(test_data_6) #[(8, 2), (10, 5), (7, 6), (6, 9), (3, 11)]
    print(test_data_7) #[(3, 11), (6, 9), (7, 6), (10, 5), (8, 2)]

    方法三:key和value分装成元祖,再进行排序

    f = zip(d.keys(), d.values())
    c = sorted(f)
    print(c)

    以上就是python中对字典按照value进行排序的三种方法,大家可以套用代码直接使用哦~

    专题推荐:python字典排序
    品易云
    上一篇:如何使用python中range()函数实现逆序遍历? 下一篇:python中如何求取字典最大值?

    相关文章推荐

    • python中如何用字典values() 方法实现字典遍历?• python中字典遍历时如何同时获得键和值?• 如何使用python中range()函数实现逆序遍历?• python中如何实现列表与字典的相互转换?• python中字典与json相互转换的方法

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网