python sorting dictionary by length of values

后端 未结 2 1475
北荒
北荒 2020-12-04 17:57

I have found many threads for sorting by values like here but it doesn\'t seem to be working for me...

I have a dictionary of lists that have tuples. Each list has a

2条回答
  •  长情又很酷
    2020-12-04 18:08

    >>> d = {"one": [(1,3),(1,4)], "two": [(1,2),(1,2),(1,3)], "three": [(1,1)]}
    >>> for k in sorted(d, key=lambda k: len(d[k]), reverse=True):
            print k,
    
    
    two one three
    

    Here is a universal solution that works on Python 2 & Python 3:

    >>> print(' '.join(sorted(d, key=lambda k: len(d[k]), reverse=True)))
    two one three
    

提交回复
热议问题