Reputation: 1694
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.
Upvotes: 0
Views: 1711
Reputation: 54168
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})
counts[x] = 1
instead, that's cheapercounts = {}
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}
There is method that could help you get nicer code
collections.defaultdict
that handles if the key isn't present (set 0, as we told him int
)
def frequency(values):
counts = defaultdict(int)
for x in values:
counts[x] += 1
return counts
the master of all collections.Counter
def frequency(values):
return Counter(values)
Upvotes: 1