0

lets say:

 a = [1,1,2,2,3,3,3,3,4,4,4,4] 

b is dict

I want b as dict which represents number of occurrence of items in a:
I want jinja2 template that create output as below.

Output of b should be, ( key - itemName, Value - corresponding item occurrence in list)

1 : 2  
2 : 2  
3 : 4  
4 : 4  

Is it possible to do via jinja2 template - i have jinja engine which renders some output i want to add this kind of stuff in template.

3 Answers3

2

You can use collection.Counter to perform these operations efficiently:

from collections import Counter
a = [1,1,2,2,3,3,3,3,4,4,4,4] 
result = dict(Counter(a)) # {1: 2, 2: 2, 3: 4, 4: 4}

for index, value in result.items():
    print(str(index) + " : " + str(value))
Corentin Pane
  • 4,794
  • 1
  • 12
  • 29
-1
count_dict = {i:a.count(i) for i in set(a)}

is that what you asked for?

music_junkie
  • 189
  • 2
  • 16
-1

You can also do this:

a = [1,1,2,2,3,3,3,3,4,4,4,4] 
frequency = {}
for i  in range(len(a)):
    frequency[a[i]] = a.count(a[i])
print(frequency)
Sheri
  • 1,383
  • 3
  • 10
  • 26