我是一名初学者,在某些代码方面遇到了麻烦。希望能有所帮助。
我有一些产品要与其他网站上的价格进行比较。麻烦的是,在每个网站中,产品名称都略有不同。我通过在excel中使用不同网站中相同产品的名称创建产品映射来解决此问题。
现在,我要创建一种电子表格,格式为:
Product Price Website B Price Website C
Product 1 Website A $5.00 $4.50
Product 2 Website A $6.99 $7.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)
“如果数据[prod_name_Website_A] .values:中的prod_name:”行会产生错误:
TypeError:类型'builtin_function_or_method'的参数不可迭代
有人对我该怎么做有任何看法吗?
谢谢。
答案 0 :(得分:1)
values是字典上的一种方法,因此您在这里看到的错误是python所说的,您不能迭代一个方法。
但是,通过调用该方法,它将返回一个迭代器,该迭代器允许您进行if-in检查。
if prod_name in data[prod_name_KN].values():
...