Python csv row count using column name
Question: I have a csv file with 'n' columns. I need to get the rowcount of each column
using the column name and give out a dictionary of the following format:

    
    
    csv_dict= {col_a:10,col_b:20,col_c:30}
    

where 10,20 and 30 are the row count of col a, b and c respectively. I
obtained a list of columns using fieldnames option of Dictreader. Now i need
the row count of every column in my list.

This is what I tried:

    
    
    for row in csv.DictReader(filename):
        col_count= sum(1 for row['col_a'] in re)+1
    

This just gets the row count of column a. How to get the row counts of all the
columns in my list and put them in a dictionary in the above mentioned format?
Any help appreciated. Thanks and regards.


Answer: 
    You can try this:  
    #Save this file with FileName.csv  
    
    Name,age,DOB
    abhijeet,17,17/09/1990
    raj,17,7/09/1990
    ramesh,17,17/09/1990
    rani,21,17/09/1990
    mohan,21,17/09/1990
    nil,25,17/09/1990
      
    #Following is the python code.
    import csv  
    from collections import defaultdict  
      
    columns = defaultdict(list) # each value in each column is appended to a list  
      
    with open('FileName.csv') as f:  
        reader = csv.DictReader(f) # read rows into a dictionary format  
        for row in reader: # read a row as {column1: value1, column2: value2,...}  
            for (k,v) in row.items(): # go over each column name and value   
                if not v=='':  
                    columns[k].append(v) # append the value into the appropriate list  
                                     # based on column name k  
      
    print len(columns['Name'])      #print the length of the specified column  
    print len(columns['age'])       #print the length of the specified column  
    print len(columns['DOB'])       #print the length of the specified column

