You should iterate over the set
of values in list_A
, because then you won't be counting over and over again (it is more efficient).
You can then add to the already created (or create then add) to the list from the key with that count a list with your element repeated the number of times it appears in list_A
.
That is to say:
dicio = {}
for elem in set(list_A):
count = list_A.count(elem)
dicio[count] = dicio.setdefault(count, []) + [elem] * count
Example:
>>> list_A = [1, 2, 2, 2, 1, 5, 1, 7, 5, 7, 3]
>>> dicio = {}
>>> for elem in set(list_A):
... count = list_A.count(elem)
... dicio[count] = dicio.setdefault(count, []) + [elem] * count
...
>>> dicio
{3: [1, 1, 1, 2, 2, 2], 1: [3], 2: [5, 5, 7, 7]}
Note that this cannot be done in what would seem the neater way of: dicio.setdefault(count, []).append([elem] * count)
, because that would append a list, not the individual elements, so instead we reassign the result of concatenating the previous list with our new elements.