如何在python字典中减去键的值

如何在python字典中减去键的值,python,dictionary,Python,Dictionary,我正在学习python,我正在尝试使用我构建的这个函数,但它不起作用。该函数在工作时不会更改字典中的单个值,尽管它应该这样做。我想得到一些帮助 def delete_product(diction): product_to_delete = raw_input() for key,value in diction.items(): if key == product_to_delete: value = value - 1

我正在学习python,我正在尝试使用我构建的这个函数,但它不起作用。该函数在工作时不会更改字典中的单个值,尽管它应该这样做。我想得到一些帮助

def delete_product(diction):
    product_to_delete = raw_input()
    for key,value in diction.items():
        if key == product_to_delete:
            value = value - 1
            if (value == 0):
                del diction[key]
            print "removed"
            raw_input()
    print "we couldnt remove the product because it does not exist"
    raw_input()

此代码段中存在错误:

value = value - 1
if (value == 0):
    del diction[key]
您只修改局部值,而不是修改字典中的值。因此,只有当值恰好为1时,此函数才会删除所需的条目

您可以按以下方式或其任何变体对其进行修改:

    if value == 1:
        del diction[key]
        break
    else:
        diction[key] = value - 1
此外,请注意,一旦条目从字典中删除,您必须跳出for循环。如果在迭代字典时对其进行修改,则迭代器在此之后将无法工作。如果要在一次迭代中删除多个关键点,请首先获取循环中要删除的所有关键点的列表,然后在循环后删除