通过添加数字来更新python字典中的值

时间:2018-10-15 09:15:27

标签: python python-3.x dictionary while-loop

我想制作一个程序,在字典中添加尚不存在的名称,并计算输入的次数。我的代码有效,但是,它不会在迭代时加1。

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)

4 个答案:

答案 0 :(得分:1)

您的检查不正确,您需要if而不是for来查看密钥是否存在,然后可以删除内部if语句

   if name in namelist:
        namelist[word] += 1
    else:
        namelist[word] = 1

答案 1 :(得分:1)

您可以改用dict.get方法来为字典的新条目提供默认值:

namelist = {}

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

答案 2 :(得分:0)

尝试

namelist = {}

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

print(namen())

print(namelist)

答案 3 :(得分:0)

没人说过字典的has_key方法,这在我看来是标准的方法:

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)