0

I want to attribute a value to a dictionary(dicio) with KEYS = count of a number in a list and VALUES = the numbers that have that count.

Just wanted to know why does this work:

for elem in list_A:

    dicio[list_A.count(elem)] = dicio.setdefault(list_A.count(elem),[]) + [elem]

and this doesn't (with either .append or .extend):

for elem in list_A:

    dicio[list_A.count(elem)] = dicio.setdefault(list_A.count(elem),[]).extend([elem])
Zé Pedro
  • 1
  • 1

1 Answers1

1

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.

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54