Python函数:遍历列表并将列表中出现的每一项内容添加到字典中

Python函数:遍历列表并将列表中出现的每一项内容添加到字典中,python,Python,我只是在做一个由Al Sweigart编写的python教科书中的练习题,我一直在想为什么我不能遍历一个列表,然后将列表中的每个项添加到一个字典项中 我正在使用一个名为add_inv的函数,通过将列表的内容添加到字典中来操作列表和现有的字典项。每次我使用for循环遍历列表时,函数只处理列表中的第一项。列表中的其余项目被add_inv函数忽略-我在add_inv函数中使用print(list_item)命令测试了这一点: def add_inv(inven,loot): inven = d

我只是在做一个由Al Sweigart编写的python教科书中的练习题,我一直在想为什么我不能遍历一个列表,然后将列表中的每个项添加到一个字典项中


我正在使用一个名为add_inv的函数,通过将列表的内容添加到字典中来操作列表和现有的字典项。每次我使用for循环遍历列表时,函数只处理列表中的第一项。列表中的其余项目被add_inv函数忽略-我在add_inv函数中使用print(list_item)命令测试了这一点:

def add_inv(inven,loot):
    inven = dict(inven)
    for list_item in loot:
        print(list_item)
        inven.setdefault(list_item, 0)
        inven[list_item] = inven[list_item] + 1
        return inven     



treasure = ['gold coin','dagger','gold coin','gold coin','ruby' ]
treasure_inv = {'gold coin': 42, 'rope': 1}
print(add_inv(treasure_inv, treasure))
#添加\u inv python函数:

def add_inv(inven,loot):
    inven = dict(inven)
    for list_item in loot:
        print(list_item)
        inven.setdefault(list_item, 0)
        inven[list_item] = inven[list_item] + 1
        return inven     



treasure = ['gold coin','dagger','gold coin','gold coin','ruby' ]
treasure_inv = {'gold coin': 42, 'rope': 1}
print(add_inv(treasure_inv, treasure))
#使用参数treasure\u inv和treasure输出print add\u inv函数:

Python 3.8.5(默认值,2020年7月28日,12:59:40) linux上的[GCC 9.3.0] 有关详细信息,请键入“帮助”、“版权”、“信用证”或“许可证”

金币

{“金币”:43,“绳子”:1}


当您从您的战利品中添加了一个物品后,您将
返回
,从而不允许您在列表
战利品上迭代

这应该可以做到:

def add_inv(inven, loot):
    inven = dict(inven)
    for list_item in loot:
        inven.setdefault(list_item, 0)
        inven[list_item] = inven[list_item] + 1

    return inven


treasure = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
treasure_inv = {'gold coin': 42, 'rope': 1}
print(add_inv(treasure_inv, treasure))
这是:

def add_inv(inven,loot):
    inven = dict(inven)
    for list_item in loot:
        if list_item not in inven:
            inven[list_item] = 1
        else:
            inven[list_item] += 1
    return inven

treasure = ['gold coin','dagger','gold coin','gold coin','ruby' ]
treasure_inv = {'gold coin': 42, 'rope': 1}
print(add_inv(treasure_inv, treasure))

#{'gold coin': 45, 'rope': 1, 'dagger': 1, 'ruby': 1}

“列表中的其余项被add_inv函数忽略”——因为您让它忽略它们。您将在循环的第一次迭代中返回。退货不应该如此缩进。在for循环中有一个退货,这只会导致处理第一个项目。谢谢,pakpe。那很好用。这是使用“if”语句填充字典而不是“setdefault”方法的替代选项。看起来“setdefault”方法不喜欢“for”循环迭代。是的,这是一种非常直接的填充字典的方法。如果它对你有用的话,考虑接受和/或推翻这个解决方案。下面是关于堆栈溢出的礼节:jån已经解释了问题所在。我应该在迭代之外返回“inven”字典。非常感谢papke,我也喜欢你的“如果”声明选项。啊,我明白了。我应该在迭代之外返回“inven”字典。非常感谢你,jån。这是一个完美的答案。没错,你明白了。