This seems to work for me, and is very close to what is given in the question. You have to return after iterating over all items (not just the first in the for-loop). Also, see that if I have an item 1 two places in the list i will add it twice to the dictionary (second addition overwriting the first), but that doesn’t matter to us. It also assumes that all iterable given (xs) has a count method to invoke.
def counts(xs):
d = {}
for item in xs:
d[item] = xs.count(item)
return d
if __name__== "__main__":
print counts([1,1,1,2,3,3,3,3,5])
print counts("abracadabra")
6
solved Defining a function with counts(xs) [closed]