【问题标题】:Filling values into mutiple dictionaries via for loop [duplicate]通过for循环将值填充到多个字典中[重复]
【发布时间】:2025-12-26 14:35:07
【问题描述】:

我正在尝试使用索引或列表:vItems = ["Yew","Magic","Maple"] 按这些名称(Yew、Magic、Maple)填充字典。我有 8 个变量会更新每个循环,我想在这 3 个字典中填写 8 个字典项(总共 24 个)。为了避免有 24 行代码,我宁愿尝试集成一个 for 循环以将其减少到 8 行。这是我目前所拥有的:

import requests
import bs4
print("Saplings script running...")

#Pulls all GE prices
vUrl = "https://prices.runescape.wiki/api/v1/osrs/1h"
headers = {
    'User-Agent': 'Calculating profit/hr methods',
    'From': ''
}
res = requests.get(vUrl , headers = headers)
soup = bs4.BeautifulSoup(res.text, 'lxml')
vText = str(res.text)

#vItems = [["Yew",5315,5373],["Magic",5316,5374],["Mahogany",21488,21480],["Maple",5314,5372],["Dragonfruit",22877,22866],["Palm",5289,5502],["Papaya",5288,5501],["Celastrus",22869,22856]]
Yew = {"SeedID":5315,"SaplingID":5373}
Magic = {"SeedID":5316,"SaplingID":5374}
Maple = {"SeedID":5314,"SaplingID":5372}

vItems = ["Yew","Magic","Maple"]

#Searches large string of text for dictionary related to item ID
vStart = vText.index("\"" + str(Yew['SeedID']) + "\"")
vStart = vText.index("{",vStart)
vEnd = vText.index("}",vStart) + 1
vSeed = eval(vText[vStart:vEnd])

#Searches large string of text for dictionary related to item ID
vStart = vText.index("\"" + str(Yew['SaplingID']) + "\"")
vStart = vText.index("{",vStart)
vEnd = vText.index("}",vStart) + 1
vSapling = eval(vText[vStart:vEnd])

# Populates Yew dictionary from values pulled online
vTest = "Yew"
Yew['Seed_avgHighPrice'] = vSeed['avgHighPrice']
Yew['Seed_highPriceVolume'] = vSeed['highPriceVolume']
Yew['Seed_avgLowPrice'] = vSeed['avgLowPrice']
Yew['Seed_lowPriceVolume'] = vSeed['lowPriceVolume']

Yew['Sapling_avgHighPrice'] = vSapling['avgHighPrice']
Yew['Sapling_highPriceVolume'] = vSapling['highPriceVolume']
Yew['Sapling_avgLowPrice'] = vSapling['avgLowPrice']
Yew['Sapling_lowPriceVolume'] = vSapling['lowPriceVolume']

# Prints results
print(Yew)
print(Yew['Seed_avgHighPrice'], Yew['Seed_highPriceVolume'], Yew['Seed_avgLowPrice'], Yew['Seed_lowPriceVolume'])

它目前只填充 Yew 的数据,但我想用 for 循环替换 Yew['asdf']。比如:

for k in vItems:
'k'['asdf'] = vSeed['asdf']

【问题讨论】:

  • for 循环存在不止一个问题。看起来压痕是主要的。
  • 还有这里的asdf 是干什么用的?

标签: python python-3.x python-requests


【解决方案1】:

我猜你正在寻找这样的东西:

y = ['hello']
z = ['world']

for item in (y, z):
    for e in ['a', 'b', 'c']:
        print(item, e)

输出:

['hello'] a
['hello'] b
['hello'] c
['world'] a
['world'] b
['world'] c

大致应用于上述特定用例,如下所示:

for prefix, item in (('Seed', vSeed), ('Sapling', vSapling)):
    for key in ('avgHighPrice', 'highPriceVolume', 'avgLowPrice', 'lowPriceVolume'):
        Yew[f'{prefix}_{key}'] = item[key]

【讨论】: