Python通过for循环向多个指定名称字典批量填充数据的实现问题
实现方案
首先优化两个基础逻辑:
- 你请求的是JSON结构接口,不需要用BeautifulSoup解析,也不需要手动切割字符串+
eval解析,直接用res.json()就能拿到结构化响应数据,性能和安全性都高很多 - 不推荐用零散独立变量存三个树种的字典,统一放到一个总字典里管理,循环时直接按key取值即可,比操作全局变量表更安全可控
完整修改后代码
import requests print("Saplings script running...") # 拉取GE价格 vUrl = "https://prices.runescape.wiki/api/v1/osrs/1h" headers = { 'User-Agent': 'Calculating profit/hr methods', 'From': '' } res = requests.get(vUrl, headers=headers) # 直接解析JSON响应,无需手动处理字符串 price_data = res.json()["data"] # 统一用总字典存所有树种配置 tree_dict = { "Yew": {"SeedID":5315,"SaplingID":5373}, "Magic": {"SeedID":5316,"SaplingID":5374}, "Maple": {"SeedID":5314,"SaplingID":5372} } vItems = ["Yew","Magic","Maple"] # 定义要提取的公共字段 extract_fields = ["avgHighPrice", "highPriceVolume", "avgLowPrice", "lowPriceVolume"] for tree_name in vItems: current_tree = tree_dict[tree_name] # 获取当前树种对应种子、树苗的价格数据 seed_price = price_data[str(current_tree["SeedID"])] sapling_price = price_data[str(current_tree["SaplingID"])] # 8行赋值逻辑完成所有字段填充,符合你的需求 current_tree["Seed_avgHighPrice"] = seed_price["avgHighPrice"] current_tree["Seed_highPriceVolume"] = seed_price["highPriceVolume"] current_tree["Seed_avgLowPrice"] = seed_price["avgLowPrice"] current_tree["Seed_lowPriceVolume"] = seed_price["lowPriceVolume"] current_tree["Sapling_avgHighPrice"] = sapling_price["avgHighPrice"] current_tree["Sapling_highPriceVolume"] = sapling_price["highPriceVolume"] current_tree["Sapling_avgLowPrice"] = sapling_price["avgLowPrice"] current_tree["Sapling_lowPriceVolume"] = sapling_price["lowPriceVolume"] # 测试输出 for tree_name in vItems: t = tree_dict[tree_name] print(f"====={tree_name}=====") print(t) print(t['Seed_avgHighPrice'], t['Seed_highPriceVolume'], t['Seed_lowPriceVolume'], t['Seed_lowPriceVolume'])
如果你一定要保留原有的Yew、Magic、Maple独立全局变量
可以通过globals()方法用字符串变量名获取全局对象,修改循环部分即可:
# 原有独立变量保留 Yew = {"SeedID":5315,"SaplingID":5373} Magic = {"SeedID":5316,"SaplingID":5374} Maple = {"SeedID":5314,"SaplingID":5372} vItems = ["Yew","Magic","Maple"] extract_fields = ["avgHighPrice", "highPriceVolume", "avgLowPrice", "lowPriceVolume"] price_data = requests.get(vUrl, headers=headers).json()["data"] for tree_name in vItems: # 通过字符串变量名获取全局字典对象 current_tree = globals()[tree_name] seed_price = price_data[str(current_tree["SeedID"])] sapling_price = price_data[str(current_tree["SaplingID"])] # 后续8行赋值逻辑和上面完全一致 current_tree["Seed_avgHighPrice"] = seed_price["avgHighPrice"] current_tree["Seed_highPriceVolume"] = seed_price["highPriceVolume"] current_tree["Seed_avgLowPrice"] = seed_price["avgLowPrice"] current_tree["Seed_lowPriceVolume"] = seed_price["lowPriceVolume"] current_tree["Sapling_avgHighPrice"] = sapling_price["avgHighPrice"] current_tree["Sapling_highPriceVolume"] = sapling_price["highPriceVolume"] current_tree["Sapling_avgLowPrice"] = sapling_price["avgLowPrice"] current_tree["Sapling_lowPriceVolume"] = sapling_price["lowPriceVolume"]
内容的提问来源于stack exchange,提问作者Yourmotor
相关产品推荐
相关产品推荐

