Home > Blockchain >  Problem with adding a value to a key in a dictionary on python
Problem with adding a value to a key in a dictionary on python

Time:07-31

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.

CodePudding user response:

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