0

My target is to count offers to specified companies in Excel.

I used plenty of if statements to do counting work before. codes like below

ipl=gs=gt=0
for file in glob.glob('*.xlsm'):
    wb=load_workbook(file,data_only=True)
    ws=wb["Tim"]
    client=ws['B2'].value

    if client=='Injection Parts Ltd.':
        ipl+=1
    if client=='Gulf Sample Ltd':
        gs+=1
    if client=='Great test Ltd.':
        gt+=1

Above worked.

Considering there are more than 20 if statments and it takes a long period time to finish checking,I used dictionary as below

ipl=gs=gt=0
for file in glob.glob('*.xlsm'):
    wb=load_workbook(file,data_only=True)
    ws=wb["Tim"]
    client=ws['B2'].value

companypool = {'Injection Parts Ltd.':ipl,
            'Gulf Sample Ltd':gs,
            'Great test Ltd.':gt}

if client in companypool:
    print(companypool[client])
    print(client)
    companypool[client]+=1

The result is that companypool[client] always being 0 and failed to count.

Any codes wrong?

I am newbie to Python,thank you in advance.

Tim Wang
  • 3
  • 1

1 Answers1

0

Are your indents correct? The block beginning with

if client in companypool:

doesn't look to be correctly indented. And the line

companypool = {'Injection Parts Ltd.':ipl,
    'Gulf Sample Ltd':gs,
    'Great test Ltd.':gt}

is going to reset your dictionary values to 0 each iteration. Move it to the start of the script.

Overall it looks like you want:

companypool = {
    'Injection Parts Ltd.': 0,
    'Gulf Sample Ltd': 0,
    'Great test Ltd.': 0,
}

for file in glob.glob('*.xlsm'):
    wb = load_workbook(file, data_only=True)
    ws = wb["Tim"]
    client = ws['B2'].value

    if client in companypool:
        print(companypool[client])
        print(client)
        companypool[client] += 1

ipl = companypool['Injection Parts Ltd.']
gs  = companypool['Gulf Sample Ltd']
gt  = companypool['Great test Ltd.']
101
  • 8,514
  • 6
  • 43
  • 69
  • Hi 101,thanks for your prompt reply. indent issue is caused by paste.sorry.Your second suggestion solved my issue halfly.It do reset my dictionary values to 0 each iteration.Actually I still need ipl,gs,gt as variate because I have to input these variate into cell of excel.If I define them to be zero,it is difficult for me to control them in future codes.I kept them but found ipl,gs,gt always being 0 instead of value of companypool[client]. – Tim Wang May 26 '16 at 06:06
  • I've added the variables at the end, hope that helps. – 101 May 26 '16 at 06:12
  • Great.It worked! Thank you.I found the result is the same.(multi-if & dictionary method).I saw below post but seems no enhancement on performance.http://stackoverflow.com/questions/17166074/most-efficient-way-of-making-an-if-elif-elif-else-statement-when-the-else-is-don – Tim Wang May 26 '16 at 06:46