user1768615
user1768615

Reputation: 281

Finding multiple occurrences of dictionary?

I'm trying to use most simple way to count all occurrences of x dictionary but without result. I cant import any library, nor use other statments than: for var in, if x, if not, if is.

Result of script should look like this: example:

list = [1,2,1,'a',4,2,3,3,5,'a',2]

code

print occurrences(list)

result

1 = [0, 2]
2 = [1, 5, 10]
a = [3, 9]
and so on

@edited corrected text

Upvotes: 0

Views: 781

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250891

OK, without using any library or function:

lis = [1,2,1,'a',4,2,3,3,5,'a',2]
dic={}
index=0
for item in lis:
    if item in dic:
        dic[item]+=[index]
        index+=1
    else:
        dic[item]=[index] 
        index+=1
print dic   

output:

{'a': [3, 9], 1: [0, 2], 2: [1, 5, 10], 3: [6, 7], 4: [4], 5: [8]}

Upvotes: 0

Oleksii Kachaiev
Oleksii Kachaiev

Reputation: 6234

>>> l = [1,2,1,'a',4,2,3,3,5,'a',2]
>>> pos = {}
>>> for i, n in enumerate(l):
...     pos.setdefault(n, []).append(i)
... 
>>> pos
{'a': [3, 9], 1: [0, 2], 2: [1, 5, 10], 3: [6, 7], 4: [4], 5: [8]}
>>> for k, v in pos.items():
...     print "%s = %s" % (k, v)
... 
a = [3, 9]
1 = [0, 2]
2 = [1, 5, 10]
3 = [6, 7]
4 = [4]
5 = [8]

Upvotes: 4

Related Questions