美文网首页
#Python-Sort dictionary by value

#Python-Sort dictionary by value

作者: 10b0bb7d9704 | 来源:发表于2016-04-23 09:39 被阅读0次

    Dictionary doesn't have an order, list has order. So, first, turn dictionary into a list of tuples. [(key1: value1), (key2, value2)....]

    dic.items()
    then sort

    import operator dic = {k1:6, k2:2, k3:4, k4:3} sorted.val.dic = sorted(dic.items(), key = operator.itemgetter(1)) #sorted by value sorted.key.dic = sorted(dic.items(), key = operator.itemgetter(0)) #sorted by keys

    相关文章

      网友评论

          本文标题:#Python-Sort dictionary by value

          本文链接:https://www.haomeiwen.com/subject/apixrttx.html