0

I'm looking to compare a list containing a sequence of numbers and a python dictionary in order to find occurrences of numbers. The behaviour of program:

  • The function occurences(L) takes as parameter a list
  • The function occurences(L) returns a dictionary whose keys are the elements of the list and the values are the number of times the element appears.
liste = []

def occurrences(liste):
    dico = {}
    for i in liste:
        for k,v in dico.items():
            if i == liste[k]:
                dico[i] = dico[i] + 1 
            else:
                dico[i] = 1
    return dico

Example of result:

>>> occurrences([1,3,2,1,4,1,2,1]) # input
{1:4,2:2,3:1,4:1} # output
TrebledJ
  • 8,713
  • 7
  • 26
  • 48

2 Answers2

1

If you're asking for an easier/more pythonic way to do this, I suggest looking at the Counter subclass from the collections library. All you would have to do to achieve your desired result is:

from collections import Counter
liste = [1,3,2,1,4,1,2,1]
n_occurences = Counter(liste) # returns {1:4,2:2,3:1,4:1}, which is 
                              # the same thing as your function occurences(liste)
v0rtex20k
  • 1,041
  • 10
  • 20
  • Also of note: `len(Counter(liste))` is the number of unique values in the list, although you could get the same information with `len(set(liste))`. – RufusVS Mar 11 '21 at 16:47
0
{i:liste.count(i) for i in set(liste)}

Shreyesh Desai
  • 569
  • 4
  • 19