Search code examples
pythondefaultdict

How can I sort a defaultdict of list by length of list


I have a defaultdict like:

d = {'a':[1], 'b':[2,3,4], 'c':[5,6]}

I expect:

sorted_d = {'b':[2,3,4], 'c':[5,6], 'a': [1]}

How can I sort it by the length of list?


Solution

  • defaultdicts - like normal dictionaries - don't have order.

    If you just want to iterate over it in a sorted way:

    for key in sorted(d, key=lambda x:len(d[x]), reverse=True):
        ...