【问题标题】:Appending values to existing keys in a dictionary将值附加到字典中的现有键
【发布时间】:2018-04-02 17:51:59
【问题描述】:

我正在开发一个网站爬虫。

这个爬虫的任务是寻找产品及其各自的品牌。 书面爬虫给了我两个列表作为输出。

到目前为止,这工作正常。 我面临的问题是我想将这两个列表放入字典中。 品牌应该是关键,产品应该是价值。 这样我就可以在这个网站上询问品牌(键)并获得产品(值)作为输出。

例如:

brands = ["a", "b", "c", "a", "a", "b"]
products = [ 1, 2, 3, 4, 5, 6]
offer = {}

for i in range(0,len(brands)-1):
    offer[brands[i]] = products[i]

想要的输出:

offer = { a: [1, 4, 5] ; b: [2, 6] ; c: [3]}

实际输出:

offer = { a: 5 ; b: 6 ; c: 3}

我有点看到for-loop 可能是问题,因为我使用的是equal-sign,这导致值正在更新,但没有追加。

感谢您的帮助

【问题讨论】:

    标签: list dictionary python-3.6


    【解决方案1】:

    你犯了正确的错误 您需要做的是将所有结果保存在一个列表中。

    brands = ["a", "b", "c", "a", "a", "b"]
    products = [ 1, 2, 3, 4, 5, 6]
    offer = {}
    
    for i in range(0,len(brands)-1):
        if brands[i] not in offer:
            offer[brands[i]] = []
        offer[brands[i]].append(products[i])
    

    您可以在使用 defaultdict 进行迭代时避免 if 条件。 defaultdict 对您的用例来说是一件很棒的事情,无需对您的代码进行太多更改,以下是这样做的方法:

    from collections import defaultdict
    
    brands = ["a", "b", "c", "a", "a", "b"]
    products = [ 1, 2, 3, 4, 5, 6]
    offer = defaultdict(list)
    
    for brand, product in zip(brands, products):
        offer[brand].append(product)
    

    【讨论】:

      猜你喜欢
      • 2020-11-23
      • 2014-06-29
      • 2021-05-17
      • 2014-04-22
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      • 2020-04-09
      • 1970-01-01
      相关资源
      最近更新 更多