代码之家  ›  专栏  ›  技术社区  ›  homersimpson

如何根据值列表的长度对python字典进行排序[重复]

  •  -1
  • homersimpson  · 技术社区  · 6 年前

    这个问题已经有了答案:

    作为一个人为的例子,我有一本字典,它是这样建立的:

    {
      'a': ['a', 'b'],
      'b': ['a', 'b', 'c'],
      'c': ['a', 'b', 'c', 'd']
    }
    

    我想按列表的长度(即每个条目的值)按降序对字典进行排序,因此结果应该是:

    {
      'c': ['a', 'b', 'c', 'd'],
      'b': ['a', 'b', 'c'],
      'a': ['a', 'b']
    }
    

    我试过这样做:

    sorted_functions = sorted(
      functions.items(),      # Sort the actual items of the dictionary
      key=len(                # Sort on the length of
        operator.itemgetter(  #   the value of the entry, which is
          slice(0, None)      #   a list slice of the whole list
        )
      ),
      reverse=True            # Sort the values in descending order
    )
    

    但是,我得到这个错误:

    TypeError: object of type 'operator.itemgetter' has no len()
    

    在回复中,我尝试了以下方法:

    >>> d = { 'a': ['a'], 'b': ['a', 'b'] }
    >>> itemgetter(slice(0, None))(d['a'])
    ['a']
    >>> len(itemgetter(slice(0, None))(d['a']))
    1
    >>> itemgetter(slice(0, None))(d['b'])
    ['a', 'b']
    >>> len(itemgetter(slice(0, None))(d['b']))
    2
    

    …所以我可以得到列表的长度,但是 sorted() 功能,不工作。

    我需要做些什么来获得 已排序() 函数按我想要的方式排序?

    3 回复  |  直到 6 年前
        1
  •  4
  •   Rakesh    6 年前

    使用 sorted 具有 key .

    前任:

    d = {
      'a': ['a', 'b'],
      'b': ['a', 'b', 'c'],
      'c': ['a', 'b', 'c', 'd']
    }
    
    print( sorted(d.items(), key= lambda x: len(x[1]), reverse=True) )
    

    输出:

    [('c', ['a', 'b', 'c', 'd']), ('b', ['a', 'b', 'c']), ('a', ['a', 'b'])]
    

    如果想维持秩序。

    import collections
    d = collections.OrderedDict(sorted(d.items(), key= lambda x: len(x[1]), reverse=True))
    print( d )
    
        2
  •  2
  •   Olivier Melançon iacob    6 年前

    使用 OrderedDict

    如果你想要的话 dict 要订购,您应该使用 订单信息 .您可以从第一个开始对项目进行排序 口述 用一个 key .

    代码

    from collections import OrderedDict
    
    d = {
      'a': ['a', 'b'],
      'b': ['a', 'b', 'c'],
      'c': ['a', 'b', 'c', 'd']
    }
    
    ordered_d = OrderedDict(sorted(d.items(), key=lambda i: -len(i[1])))
    
    print(ordered_d)
    

    输出

    OrderedDict([('c', ['a', 'b', 'c', 'd']), ('b', ['a', 'b', 'c']), ('a', ['a', 'b'])])
    

    蟒蛇3.6+ 口述 已订购

    尽管如此,如果使用python 3.6+,插入顺序将保留为 口述 .这是特定于cpython实现的,并且将仅是 official language feature starting at version 3.7 .

    代码

    d = {
      'a': ['a', 'b'],
      'b': ['a', 'b', 'c'],
      'c': ['a', 'b', 'c', 'd']
    }
    
    ordered_d = dict(sorted(d.items(), key=lambda i: -len(i[1])))
    
    print(ordered_d)
    

    输出

    {'c': ['a', 'b', 'c', 'd'], 'b': ['a', 'b', 'c'], 'a': ['a', 'b']}
    
        3
  •  0
  •   Taohidul Islam    6 年前

    你可以用 lambda .比如:

    my_dict = {
      'a': ['a', 'b'],
      'b': ['a', 'b', 'c'],
      'c': ['a', 'b', 'c', 'd']
    }
    sorted_list = sorted(my_dict.items(), key= lambda value: len(value[1]), reverse=True) #you will get a sorted list,reverse=True will bring longer lists to appear first
    print(sorted_list)
    sorted_dict = {x[0]:x[1] for x in sorted_list} #convert your sorted list into dictionary
    print(sorted_dict)
    

    或者你也可以不用听写理解,就像阿兰·费伊说的那样:

    sorted_dict = dict(sorted_list)