Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python sorting dictionary by length of values

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 different amount of tuples. I want to sort the dictionary by how many tuples each list contain.

>>>to_format  >>>{"one":[(1,3),(1,4)],"two":[(1,2),(1,2),(1,3)],"three":[(1,1)]} >>>for key in some_sort(to_format):        print key, >>>two one three 

Is this possible?

like image 461
jwillis0720 Avatar asked Jun 01 '13 02:06

jwillis0720


1 Answers

>>> 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 
like image 66
jamylak Avatar answered Oct 08 '22 00:10

jamylak