gpt4 book ai didi

python - 将列表中的元素添加到字典并增加值

转载 作者:太空宇宙 更新时间:2023-11-04 07:29:21 25 4
gpt4 key购买 nike

我有字典和列表。列表仅包含项目,字典包含项目以及我有多少给定项目。我想要做的是遍历字典和列表,如果字典中的键与列表中的项目相同,我只想将其值更新 1,但如果没有我想要的相同项目将项目表单列表添加到dict并将其值设置为1。

stock = {apple: 1, banana: 4, orange: 10}
delivery = [apple, apple, grapefruit]

for k, v in stock.items():
for item in delivery:
if item == stock[k]:
stock[v] += 1
else:
stock.update({item:1})

输出应该是这样的:

stock = {apple: 3, banana: 4, orange: 10, grapefruit: 1}

但是我收到消息:字典在迭代期间改变了大小

最佳答案

您不应该在遍历 dictlist 时更改它。您可以像这样编写代码:

stock = {'apple': 1, 'banana': 4, 'orange': 10}
delivery = ['apple', 'apple', 'grapefruit']

for item in delivery:
if item in stock:
stock[item] +=1
else:
stock[item] = 1

print(stock)

关于python - 将列表中的元素添加到字典并增加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51123094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com