1

I am looking for an efficient way to take a list that has several elements with 2 or more occurrences, and convert into a dictionary where the value equals the number of occurrences.

Example list:

l = ['dog', 'bird', 'bird', 'cat', 'dog', 'fish', 'cat', 'cat', 'dog', 'cat', 'bird', 'dog']

l_dict = {'dog':4, 'bird': 3, 'cat': 4, 'fish': 1}

Any suggestions is appreciated. Thanks.

Cubix48
  • 2,607
  • 2
  • 5
  • 17
dmd7
  • 605
  • 3
  • 8
  • 2
    As mentioned here, just use `Counter` [How can I count the occurrences of a list item?](https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item) – shriakhilc Apr 01 '22 at 15:29
  • 1
    What have you tried? SO can help you with specific questions, but is not a code-writing service. [ask] – Chris Apr 01 '22 at 15:32
  • Why did you include `'fish'` while you said *"2 or more occurrences"*? – S.B Apr 01 '22 at 15:35

3 Answers3

7

here's a 1 liner for this purpose using the Counter function from collections library:

from collections import Counter
l = ['dog', 'bird', 'bird', 'cat', 'dog', 'fish', 'cat', 'cat', 'dog', 'cat', 'bird', 'dog']

print(Counter(l))
gil
  • 2,388
  • 1
  • 21
  • 29
1

The solution suggested by gil is good. The following solution also work :

l_dict = {key: l.count(key) for key in set(l)}

Using counter is more effective for large lists, but dict comprehension is better for shorter lists.

We can verify it with timeit :

from timeit import timeit
from collection import Counter

# declare your list here

def with_comprehension():
    return {key: l.count(key) for key in set(l)}

def with_counter():
    return Counter(l)

With your example (12 elements), dict comprehension is better :

>>> timeit(with_comprehension)
0.9273126000771299
>>> timeit(with_counter)
1.1477947999956086

But when you have 100 elements, counter become more effective :

>>> timeit(with_comprehension)
3.6719840000150725
>>> timeit(with_counter)
2.85686399997212 
imperosol
  • 584
  • 4
  • 14
0

A native implementation, would be to go through the array and count the amount of repeated elements but verifying that they do not exist before in the dictionary, if so, then increase the counter, in a super simple way, you have something like this

l = ['dog', 'bird', 'bird', 'cat', 'dog', 'fish', 'cat', 'cat', 'dog', 'cat', 'bird', 'dog']

l_dict = {}

for i in l:
    if i in l_dict:
        l_dict[i] += 1
    else:
        l_dict[i] = 1

print(l_dict)
Sergio Ribera
  • 126
  • 2
  • 5