views:

165

answers:

4

Hi, I've got a problem , and do not know how to code in python.

I've got a list[10, 10, 10, 20, 20, 20, 30]

I want it be in a dictionary like this

{"10": 1, "20":  3, "30" : 1}

How could I achieve this?

+1  A: 

Like this

l = [10, 10, 10, 20, 20, 20, 30]
uniqes = set(l)
answer = {}
for i in uniques:
    answer[i] = l.count(i)

answer is now the dictionary that you want

Hope this helps

inspectorG4dget
+8  A: 
from collections import Counter
a = [10, 10, 10, 20, 20, 20, 30]
c = Counter(a)
# Counter({10: 3, 20: 3, 30: 1})

If you really want to convert the keys to strings, that's a separate step:

dict((str(k), v) for k, v in c.iteritems())

This class is new to Python 2.7; for earlier versions, use this implementation:

http://code.activestate.com/recipes/576611/


Edit: Dropping this here since SO won't let me paste code into comments,

from collections import defaultdict
def count(it):
    d = defaultdict(int)
    for j in it:
        d[j] += 1
    return d
Glenn Maynard
+3  A: 

Another way that does not use set or Counter:

d = {}
x = [10, 10, 10, 20, 20, 20, 30]
for j in x:
    d[j] = d.get(j,0) + 1

EDIT: For a list of size 1000000 with 100 unique items, this method runs on my laptop in 0.37 sec, while the answer using set takes 2.59 sec. For only 10 unique items, the former method takes 0.36 sec, while the latter method only takes 0.25 sec.

EDIT: The method using defaultdict takes 0.18 sec on my laptop.

Steve
If this is a performance race, check the defaultdict version I put in my answer (blame SO for not letting me paste it here), which is about twice as fast.
Glenn Maynard
Thanks for the comment. You are exactly right: your method ran in 0.18 sec on my laptop.
Steve
+1  A: 

in Python >= 2.7 you can use dict comprehensions, like:

>>> l = [10, 10, 10, 20, 20, 20, 30]
>>> {x: l.count(x) for x in l}
{10: 3, 20: 3, 30: 1}

not the fastest way, but pretty suitable for small lists

UPDATE

or, inspired by inspectorG4dget, this is better:

{x: l.count(x) for x in set(l)}
mykhal