pythonic way of splitting a list of lists into a length-keyed dictionary?

dictionary, list, python, python-3.x

Solution

from itertools import groupby

xs_dict = {
    key: list(value)
    for (key, value) in groupby(sorted(xs, key=len), len)
}

As discussed in the comments below, the necessary sorting of the input is a step which is unnecessary costly. For large input this will slow down this algorithm way more than necessary. Consider using @hiroprotagonist's solution instead then, or replace the `groupby(sorted(…), …)` by a `groupby()` which can handle unsorted input.

Problem

``` xs = [ [1,2,3,4], [5,6,7,8], [9,0,0,1], [2,3], [0], [5,8,3,2,5,1], [6,4], [1,6,9,9,2,9] ] """ expected output: xs_dict = { 1: [[0]] 2: [[2,3],[6,4]] 4: [[1,2,3,4],[5,6,7,8],[9,0,0,1]] 6: [[5,8,3,2,5,1],[1,6,9,9,2,9]] } """ ``` I can do this, for example, by ``` xs_dict = {} for x in xs: aux = xs_dict.get(len(x),[]) aux.append(x) xs_dict[len(x)] = aux print(xs_dict) ``` But I can't help feeling there should be a more pythonic way to achieve this. What is it?

Original source