Finding data in nested dictionaries: TypeError: argument of type 'builtin_function_or_method' is not iterable

Finding data in nested dictionaries: TypeError: argument of type 'builtin_function_or_method' is not iterable

我是初学者,在使用某些代码时遇到了一些问题。非常感谢您的帮助。

我尝试比较不同网站上的价格的产品。问题是每个网站的产品名称都略有不同。我通过在 excel 中使用不同网站中相同产品的名称创建产品映射来解决这个问题。

现在我想创建一个格式如下的电子表格:

Product                    Price Website B            Price Website C
Product 1 Website A              .00                       .50
Product 2 Website A              .99                       .89

我从网站上抓取了价格并创建了一个电子表格,其中包含原产地网站、该网站上的产品名称和该网站上的价格。

我正在尝试执行以下操作:

import openpyxl
import pprint

'''
Set up an empty dictionary which will have the following format:

data = {'product_name1_Website_A':
                {'product_name1_Website_B': price1_Website_B, 
                 'product_name1_Website_C': price1_Website_C
                },
        'product_name2_Website_A':
                {'product_name2_Website_B': price2_Website_B, 
                 'product_name2_Website_C': price2_Website_C
                },
        ...
            }

'''
data = {}

files = {'Name_Mapping':'Name_Mapping.xlsx',
         'Scan Prices':'price_scan.xlsx'
         }

wb1 = openpyxl.load_workbook(files['Name_Mapping'])                   
wb2 = openpyxl.load_workbook(files['Scan Prices'])                   

sheet1 = wb1.get_sheet_by_name('Product Name Mapping')
sheet2 = wb2.get_sheet_by_name('Sheet')

# Creating the dictionary structure.
for row in range(2, sheet1.max_row + 1):
    prod_name_Website_A = sheet1['A' + str(row)].value
    prod_name_Website_B = sheet1['B' + str(row)].value
    prod_name_Website_C = sheet1['C' + str(row)].value
    data[prod_name_Website_A] = {}
    # Set default prices to zero for now
    data[prod_name_Website_A][prod_name_Website_B] = 0                          
    data[prod_name_Website_A][prod_name_Website_C] = 0                           

    # Search the spreadsheet containing the prices and bring those in 
    # to be added to dictionary.
    # I had to put this for loop inside the previous one because calling
    # data[prod_name_Website_A].values caused an issue due to local variable.
    for line in range(2, sheet2.max_row + 1):
        store = sheet2['A' + str(row)].value
        prod_name = sheet2['B' + str(row)].value
        price = sheet2['C' + str(row)].value
        if prod_name in data[prod_name_Website_A].values:
            data[prod_name_Website_A][prod_name] = price

pprint.pprint(data)

第 'if prod_name in data[prod_name_Website_A].values:' 行产生错误:

TypeError: 'builtin_function_or_method' 类型的参数不可迭代

有人对我如何做到这一点有任何看法吗?

谢谢。

values 是字典上的一个方法,所以你在这里看到的错误是 python 说,你不能迭代一个方法。

然而,通过调用该方法,它 returns 一个允许您进行 if-in 检查的迭代器。

if prod_name in data[prod_name_KN].values():
...