Problem with adding a value to a key in a dictionary on python

Question:

I have a dictionary called counts:

counts = dict()
names = ['David', 'Daniel', 'Michelle', 'Daniel', 'Ben', 'Ben', 'Daniel']
for name in names:
    if name not in names:
        counts[name] = 1
    else:
        counts[name] = counts[name] + 1
print(counts)

What is going wrong? I am not sure why it is not working.

Asked By: Apple Pie

||

Answers:

small error, should be if name not in counts:

counts = dict()
names = [‘David’, ‘Daniel’, ‘Michelle’, ‘Daniel’, ‘Ben’, ‘Ben’, ‘Daniel’]
for name in names:
if name not in counts:
counts[name] = 1
else:
counts[name] = counts[name] + 1

Answered By: Bob Parkinson Jr
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.