将值附加到字典中的现有键

时间:2018-04-02 17:51:59

标签: list dictionary python-3.6

我正在使用网站抓取工具。

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

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

e.g:

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 - 循环可能是问题,因为我使用的是equal - 符号,这导致值正在更新,但没有附加。

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

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

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:
        offers[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)
相关问题