我有一系列非常长的网址,其中的密钥格式为myurls21,1
,myurls21,2
等,我使用以下语句将其分解为组件:
import concurrent.futures
import urllib.request
import json
myurls2 = {}
for x in range(1, 15):
for y in range(1, 87):
strvar1 = "%s" % (x)
strvar2 = "%s" % (y)
with open("C:\\Python33\\NASDAQ Stock Strings\\NASDAQ_Config_File_{}_{}.txt".format(x,y),"r") as f:
myurls2[x,y] = f.read().replace('\n', '')
#print("myurls_" + str(strvar1) + "_" + str(strvar2) + "=", myurls2[x,y])
#print(myurls2[x,y])
URLS = myurls2.values()
# Retrieve a single page and report the url and contents
def load_url(url, timeout):
conn = urllib.request.urlopen(url, timeout=timeout)
return conn.readall()
# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
# Start the load operations and mark each future with its URL
future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
c = 0
for future in concurrent.futures.as_completed(future_to_url):
url = future_to_url[future]
a = ''
b = ''
c += 1
for url in URLS:
a = url.rsplit("=", 1)[-1]
print(myurls2.keys())
如何打印拆分到日志中的每个URL的密钥?我已经尝试了print(myurls2.keys())
,但它会打印存储在字典中的所有密钥(URLS是根据myurls2
字典的内容定义的。)
答案 0 :(得分:1)
如果要迭代字典中的键和值,可以这样做:
for key, url in myurls2.items():
print(key)
a = url.rsplit("=", 1)[-1]
如果您想要传递给concurrent
的网址的密钥,请重构以允许:
future_to_url = {executor.submit(load_url, url, 60): (key, url)
for key, url in myurls2.items()}
现在您可以访问它了:
for future in concurrent.futures.as_completed(future_to_url):
key, url = future_to_url[future]
# print key and process url