2

I have a list like this:

my_list = [1, 1, 1, 1, 1, 2, 2, 2, 3]

and I want to make a dictionary like this:

result = {1: 5, 2: 3, 3: 1}
# key is unique list items
# and value is the times they have been repeated in list

I could get this done by this piece of code but doesn't look good:

def parse_list(my_list):
    result = {}
    my_set = set(my_list)
    for i in my_set:
        result[i] = len([j for j in my_list if j == i])
    return result

I think this should be achievable with less loops. Any idea?

Taxellool
  • 4,063
  • 4
  • 21
  • 38

1 Answers1

4

You can use collections.Counter:

>>> from collections import Counter
>>> my_list = [1, 1, 1, 1, 1, 2, 2, 2, 3]
>>> Counter(my_list)
Counter({1: 5, 2: 3, 3: 1})

>>> dict(Counter(my_list))
{1: 5, 2: 3, 3: 1}
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 1
    @Taxellool: Note that `Counter` inherits from `dict` so you can use it just like a `dict`. So that final conversion step isn't really necessary, but I guess if you're making lots of these things a plain `dict` uses a little bit less memory than a `Counter`. – PM 2Ring Jan 19 '15 at 13:39