【发布时间】:2017-12-13 04:00:08
【问题描述】:
我正在使用 python 运行一个 for 循环来打印特定 URL 中的每个值,但是每个值都打印到具有相同键的新字典,而不是在一个字典中插入多个值。
如何将特定键的所有值插入到单个唯一键中?
kernelLinks = []
for values in output:
links = links + ([("https://www.kaggle.com" + (values["scriptUrl"]))])
driver = webdriver.Chrome()
method = {}
dictionary = []
for url in links:
driver.get(url)
driver.switch_to_frame(driver.find_element_by_tag_name("iframe"))
data = driver.page_source
data2 = BeautifulSoup(data, "lxml")
for a in data2.find_all('span', class_="n"):
data2 = BeautifulSoup(data, "lxml")
dictionary = {}
kernel = url
method = a.text
dictionary[kernel] = method
print(dictionary)
当前输出:
{'https://www.kaggle.com/kanncaa1/data-sciencetutorial-for-beginners': 'check_output'} {'https://www.kaggle.com/kanncaa1/data-sciencetutorial-for-beginners': '数据'} {'https://www.kaggle.com/kanncaa1/data-sciencetutorial-for-beginners': '解码'} .....
想要的输出:
{'https://www.kaggle.com/kanncaa1/data-sciencetutorial-for-beginners': 'check_output', 'data', 'decode}
【问题讨论】:
-
什么是
dictionary1?url在哪里定义?看起来url来自之前的for循环,该循环已经运行完成,因此您将获得url的最后一个值。或者,第二个for循环实际上是否缩进到第一个循环中? -
欢迎来到 Stack Overflow。阅读如何创建minimal reproducible example。您的大部分代码与问题的本质无关。尝试编写一些代码来测试您对循环的理解,因为您每次都重新创建一个新字典。另外,看看
defaultdict -
请提供更多关于您的变量的上下文以及所需的输出?
-
抱歉,我已经更新了问题。我正在尝试将当前键(kaggle url)更改为包含当前单独打印的所有值的唯一键。
标签: python dictionary for-loop printing key-value