【问题标题】:Sort a dict by numeric value of dict.values按 dict.values 的数值对 dict 进行排序
【发布时间】:2013-02-21 01:08:40
【问题描述】:

我有一个字典d = {'a': '1', 'c': '10', 'b': '8', 'e': '11', 'g': '3', 'f': '2'}。我想用d.values() 的数值对字典进行排序。必需的答案是['a','f', 'g', 'b', 'c', 'e']。我检查了 here 。我无法根据 d.values() 的整数值对其进行排序。

【问题讨论】:

    标签: python sorting dictionary


    【解决方案1】:
    >>> d = {'a': '1', 'c': '10', 'b': '8', 'e': '11', 'g': '3', 'f': '2'}
    >>> sorted(d, key=lambda i: int(d[i]))
    ['a', 'f', 'g', 'b', 'c', 'e']
    

    【讨论】:

      【解决方案2】:

      这是因为字典中的值是string 类型的:请注意数字周围的引号。尝试将您的字典设置为:

      d = {'a':1, 'c':10, 'b':8, 'e':11, 'g':3, 'f':2}
      

      【讨论】:

        猜你喜欢
        • 2011-08-09
        • 2020-03-16
        • 1970-01-01
        • 1970-01-01
        • 2011-03-25
        • 1970-01-01
        • 2022-06-17
        • 1970-01-01
        • 2021-10-19
        相关资源
        最近更新 更多