Ad

Update Value In Python Dictionary By Adding A Number

- 1 answer

I want to make a program that adds a name in the dictionary if it doesn't exist already and count the times it is given as input. My code works, however, it doesn't add 1 when it iterates.

namelist = {}

def namen():
    while True:
        word = input('Vul een naam in: ')
        if word == '':
            break
        else:
            for name in namelist:
                if word == name:
                    namelist[word] += 1
                # else wasn't properly indented earlier
                else:
                    namelist[word] = 1


print(namen())

print(namelist)
Ad

Answer

No one said anything about the has_key method of dictionaries, which is in my opinion the standard way to to this:

namelist = {}

def namen():
    while True:
        word = input('Vul een naam in: ')
        if word == '':
            break
        else:
            if namelist.has_key(word):
                namelist[word] += 1
            else:
                namelist[word] = 1

print(namen())

print(namelist)
Ad
source: stackoverflow.com
Ad