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

Viewed 30

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.

1 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

Related