-1

i was trying to keep count of each item in list in python and want to convert it into key-value pairs like json so i can able to iterate over it to present it on frontend using django.

list = ["a" , "a", "c",  "b", "c", "d"]

here same i want this list into key value pairs with counting of each item in list

list = [{ "name":"a" , "count":2 } , { "name":"c" , "count":2 , ......}]
Siddhesh
  • 61
  • 6

3 Answers3

3

Use a set to count the number of each element in the list

l = ["a" , "a", "c",  "b", "c", "d"]
d = {val: l.count(val) for val in set(l)}

this will give you :

{'c': 2, 'a': 2, 'b': 1, 'd': 1}

If you want to format the dict as you wrote it in your message (even though it's really inefficient), you can write it like that :

d = [{'name': val, 'count': l.count(val)} for val in set(l)}]
imperosol
  • 584
  • 4
  • 14
2
data = ["a" , "a", "c",  "b", "c", "d"]
count_list=[{"name":d,"count": data.count(d)} for d in set(data)]

noobmaster
  • 21
  • 1
  • 1
1

Probably the easiest way to do this:

def dict_count(list):
    dict_tot = {}
    for i in liste:
        dict_tot[i] = liste.count(i)
    print(dict_tot)