Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何解决这个问题?RuntimeError:字典在迭代期间更改了大小_Python_Python 3.x_Dictionary - Fatal编程技术网

Python 如何解决这个问题?RuntimeError:字典在迭代期间更改了大小

Python 如何解决这个问题?RuntimeError:字典在迭代期间更改了大小,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,当我在函数中使用向字典添加一个项时,它给出了以下错误: inv = { "rope": 1, "torch": 6, "gold coin": 42, "dagger": 1, "arrow": 12 } dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] def AddInventory(invloop, lst): for item in lst: for k,v in invloop.it

当我在函数中使用
向字典添加一个项时,它给出了以下错误:

inv = { "rope": 1, "torch": 6, "gold coin": 42, "dagger": 1, "arrow": 12 }
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def AddInventory(invloop, lst):
  for item in lst:
    for k,v in invloop.items():
      if item == k:
        v += 1
      else:
        invloop[item] = 1
  return(invloop)
inv = AddInventory(inv, dragonLoot)

事实上,您不应该在循环时将项目添加到库存中。更重要的是,您不需要内部循环,因为字典的优点是您可以通过键直接访问:您可以使用
in
操作符测试它是否有键

因此,请改为:

def AddInventory(invloop, lst):
    for item in lst:
        if item in invloop:
            invloop[item] += 1
        else:
            invloop[item] = 1
    return(invloop)