I’m trying to count the frequency from a list. I received an type error
mylist = [1, 1, 1, 2, 3, 3, 4]
def frequency(x):
counts = dict()
if x in counts:
counts[x] += 1
elif len(counts) < 3:
counts.update([x, 1])
return counts
for x in mylist:
frequency(x)
I received TypeError: cannot convert dictionary update sequence element #0 to a sequence on counts.update([x, 1]). I checked what this error is about, but I cannot see I violated it.
>Solution :
Fix
The counts should be created outside, so before, if you create it in the method, that will be new one each time
You may update a dict with another dict, not a list
counts.update({x: 1})
Improve logic
- simply do
counts[x] = 1instead, that’s cheaper - it woul be better that the method does the whole frequency computation, from a list
counts = {}
def frequency(values):
for x in values:
if x in counts:
counts[x] += 1
else:
counts[x] = 1
return counts
mylist = [1, 1, 1, 2, 3, 3, 4]
counts = frequency(mylist)
print(counts) # {1: 3, 2: 1, 3: 2, 4: 1}
Improve code
There is method that could help you get nicer code
-
collections.defaultdictthat handles if the key isn’t present (set 0, as we told himint)def frequency(values): counts = defaultdict(int) for x in values: counts[x] += 1 return counts -
the master of all
collections.Counterdef frequency(values): return Counter(values)