首页 > 解决方案 > 如何有效地遍历大量字典引用?

问题描述

我遇到的问题可能有一个简单的解决方案,但我已经尝试了我所知道的一切。

我正在尝试编写一个程序来自动计算在 Satisfactory 中建立工厂的最有效方法,并且在尝试引用项目及其食谱的字典时,我收到了这个错误:

Traceback (most recent call last):
  File "C:\Users\name\Desktop\Codes\Python Testing\satisfactory.py", line 56, in <module>
    main(item)
  File "C:\Users\name\Desktop\Codes\Python Testing\satisfactory.py", line 54, in main
    mainrq1a = itemList[item]['rqAmounts'][i]
KeyError: 0

对于上下文,我正在尝试将项目 1 中的主要所需金额设置为此处字典的值:

"steelingot": {
    "name": "Steel Ingot",
    "minAmount": 1,

    "rq": {
        "rq1": "ironore",
        "rq2": "coalore"
    },

    "rqAmounts": {
        "rq1a": 1,
        "rq2a": 1
    },

    "builtBy": "foundry"
}

这是我正在使用的代码:

for i in range(len(rqAll) - 2):
     try: itemList[rqAll[i]]['isBasic']
     except:
         print("more to come")
     else:
         mainrq1a = itemList[item]['rqAmounts'][i]
         print(mainrq1a)

这将遍历所需列表中的每个项目 (rqAll) 并检查它是否是基本项目。如果是的话,它应该需要制作该物品所需的数量,但这就是我的问题所在。

谢谢阅读!

标签: pythondictionary

解决方案


推荐阅读