Python将csv读入dict

时间:2016-12-09 15:38:18

标签: python csv

我无法在“参考”中阅读我的词典。

enter image description here

这里是123.csv:

BrandName,LineCode,PartNo,ShortDescription,SuperStock,DropshipStock,Price,Core
Carter,5C,M3643,FILTER,0,0,14.8,0
Carter,5C,M3805,FILTER,1,0,14.8,0
Carter,5C,M4512,FILTER,2,0,14.8,0
Carter,5C,M4642,FILTER,3,0,14.8,0
Carter,5C,M60088,FILTER,4,0,14.8
Carter,5C,M60142,FILTER,6,0,14.8
Carter,5C,M60167,FILTER,7,0,14.8,0

和abc.csv:

productcode,book_isbn,stockstatus,Price,Core,AddtoCartBtn_Replacement_Text,Availability
5CM2195,5CM2195,,,,,
5CM2846,5CM2846,,,,,
5CM3643,5CM3643,,,,,
5CM3805,5CM3805,,,,,
5CM4512,5CM4512,,,,,
5CM4642,5CM4642,,,,,
5CM60088,5CM60088,,,,,
5CM60142,5CM60142,,,,,
5CM60167,5CM60167,,,,,

我是否正确地将csv读入paRefefence dict?

c = csv.reader(open(pluginPath + "123.csv"))
d = csv.reader(open(pluginPath + "abc.csv"))

paReference ={}
for item in c:
    if item[1] not in paReference:
        paReference =[item[0]] = [item[1] + item[2].replace('-','')]
    else:
        paReference[item[1]].append(item[0])
    print(item)

for item in d:
    if item[0] not in paReference:
        print ("Not Found! " + item[0])
    else:
        print ("Found! " + item[0])

我是python的新手我很难理解为什么它找到了一个零件号而不是其他零件号。任何建议都有帮助!

1 个答案:

答案 0 :(得分:2)

来自第二个csv的productcode似乎是来自第一个csv的LineCodePartNo。看起来您正在根据您构建的字典的键检查productcode。看起来您使用产品代码作为键,品牌名称作为值?如果是这种情况,这应该有用。

paReference = {}
for item in c:
    pcode = item[1] + item[2].replace('-','')
    if pcode not in paReference:
        paReference[pcode] = [item[0]]
    else:
        paReference[pcode].append(item[0])
    print(item)

for item in d:
    if item[0] not in paReference:
        print ("Not Found! " + item[0])
    else:
        print ("Found! " + item[0])

如果这不是您的预期用途,请发表评论。