Reputation: 2834
I am trying to write a function that takes an array and returns a dictonary with keys that denote the unique values in the list and a value that is the count of each item in the list.
def freq(arr):
sum = 0
dict = {}
for i in arr:
if i not in dict:
dict[i] = 1
else:
dict[i] =+ 1
return dict
print(count([1,2,3,4,5,100,100,1000]))
{1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 1000: 1, 100: 1}
I was hoping for
{1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 1000: 1, 100: 2}
Upvotes: 3
Views: 7529
Reputation: 117
So, to reduce the code, and make it more readable, you can just use a default dict instead. To use the default dict, you first have to import it from the collections module and then create the default dict object. The default dictionary requires me to give it something called a factory function. In this case, I'll give it the integer class, and that's essentially going to act as the creator of the default value so that if I try to access a key that doesn't exist, it will create a default value for me using this object as the constructor, and since creating a new int object initializes the value to zero, I can now just access any key, and increment it without checking to see if it's already there.
So you have to import the defaultdict first.
from collections import defaultdict
# your list of numbers
nums = [1,2,3,4,5,100,100,1000]
# use a default dictionary to count each element
numCounter = defaultdict(int)
# Count the elements in the list
for num in nums:
numCounter[num] += 1
# print the result
for (k, v) in numCounter.items():
print(str(k) + ": " + str(v))
The output will be
1:1,
2:1,
3:1,
4:1,
5:1,
100:2,
1000:1
Upvotes: 0
Reputation: 47790
collections.Counter
already does what you want.
from collections import Counter
c = Counter([1,2,3,4,5,100,100,1000])
print(c)
# Counter({100: 2, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 1000: 1})
Upvotes: 9