【问题标题】:Single key printing for each value每个值的单键打印
【发布时间】: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}

【问题讨论】:

  • 什么是dictionary1url 在哪里定义?看起来url 来自之前的for 循环,该循环已经运行完成,因此您将获得url 的最后一个值。或者,第二个for 循环实际上是否缩进到第一个循环中?
  • 欢迎来到 Stack Overflow。阅读如何创建minimal reproducible example。您的大部分代码与问题的本质无关。尝试编写一些代码来测试您对循环的理解,因为您每次都重新创建一个新字典。另外,看看defaultdict
  • 请提供更多关于您的变量的上下文以及所需的输出?
  • 抱歉,我已经更新了问题。我正在尝试将当前键(kaggle url)更改为包含当前单独打印的所有值的唯一键。

标签: python dictionary for-loop printing key-value


【解决方案1】:

我认为您问题的相关部分是:

如何将特定键的所有值插入到单个唯一键中?

您可能希望使用另一个数据结构来保存不同的值。 例如 set 如果您只对有哪些不同的值感兴趣,而不是重复的值。 (如果您想跟踪所有值,请切换到 list 并使用 append 而不是 add。)此答案演示了如何跟踪分配给您要解析的页面上不同 html 元素的 css 类。它假定您已经以某种方式获得了元素及其类。

items = [
    ('span', 'pretty'),
    ('div', 'listing'),
    ('div', 'header'),
    ('span', 'ugly'),
    ('div', 'footer'),
]

data = dict()
for elem, css_class in items:
    classes = data.setdefault(elem, set())
    classes.add(css_class)

print data

这个推测性的答案可能会让你继续前进。除此之外,请查看上面的 cmets,尤其是 https://stackoverflow.com/help/mcve,正如 @peter-wood 在他的评论中已经提到的那样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-17
    • 2020-04-20
    • 1970-01-01
    • 2013-11-10
    • 2017-02-27
    • 1970-01-01
    相关资源
    最近更新 更多