1

I have a file in .csv with contains ht:

1,winter
2,autumn
3,winter
4,spring
5,summer
6,autumn
7,autumn
8,summer
9,spring
10,spring

I need to parse this file to generate one containing :

winter = 1,3
autumn = 2,6,7
spring = 4,9,10
summer = 5,8

I find this post How to print count of occourance of some string in the same CSV file using Python? but I could not adapt to what I want.

I appreciate any help or guidance to address this concern.

Thanks.

Community
  • 1
  • 1

1 Answers1

0

create an empty dict and open csv and read each row.
while reading each row check if row[1] in dict.
Else add it to the dict, create a list with the value row[0]. If that is already present append the value to the dict.
Something like this.

import csv
try :
    fr = open("mycsv.csv")
except:
    print "Couldn't open the file"
reader = csv.reader(fr)
base={}
for row in reader :
     if len(row) > 0:
            if row[1] in base: #Check if that season is in dict.
                    base[row[1]].append(row[0]) # If so add the number to the list already there.
            else:
                    base[row[1]]=[row[0]] # Else create new list and add the number
print base  

It gives output something like this.
{'autumn': ['2', '6', '7'], 'spring': ['4', '9', '10'], 'winter': ['1', '3'], 'summer': ['5', '8']}

sudheesh shetty
  • 358
  • 4
  • 14