Skip to content Skip to sidebar Skip to footer

Inner For Loop Is Not Executed In Python

i have inputs.csv like below apple 400 banana 401 mango 430 orange 440 banana 401 orange 440 mango 430 apple 400 orange 440 banana 401 i want my output like outp

Solution 1:

Thanks for the input , i modified the code like below

for k, v in cn.items():
         print("k compared is::",k)
         withopen('new.csv','r') as csvinput:
              reader = csv.reader(csvinput)
              for row in reader:
                  print("Executing inner loop")
                  print("row value compared is ::",row[0])
                  if k == row[0] :
                     print("matched")
                     row.append(v)
                     all.append(row)
                     break
writer.writerows(all)

with this code it worked but my worry is csv file will be opened and read for k number of times , so is there any better solution

Solution 2:

I think the following code will work

import csv
from collections import Counter
from operator import itemgetter
withopen('new.csv','r') as csvinput:
    reader = csv.reader(csvinput)
    cn = Counter()
    for row in reader:
        trow=tuple(row)
        cn[trow] += 1print cn
withopen('update.csv', 'w') as csvoutput:
    writer = csv.writer(csvoutput)
    for row in cn:
        writer.writerow([row[0],row[1],cn[row]])

Post a Comment for "Inner For Loop Is Not Executed In Python"