Q:

python create dictionary from csv

import csv

with open('coors.csv', mode='r') as infile:
    reader = csv.reader(infile)
    with open('coors_new.csv', mode='w') as outfile:
        writer = csv.writer(outfile)
        mydict = {rows[0]:rows[1] for rows in reader}
2
mydict = {y[0]: y[1] for y in [x.split(",") for x in open('file.csv').read().split('\n') if x]}
1
# Function to write to CSV from Dictionary
# filename is hours.csv
#list hours is
import csv
from collections import OrderedDict

list_hours=[{'Name':'Nagendra Babu','Hrs':8,'BHrs':6,'NBHrs':2},
            {'Name':'Nitesh Bangera','Hrs':6,'BHrs':6,'NBHrs':0},
            {'Name':'Sathya Narayana','Hrs':8,'BHrs':5,'NBHrs':3},
            {'Name':'Ashok Gattu','Hrs':8,'BHrs':8,'NBHrs':0},
            {'Name':'Praveen Kumar','Hrs':8,'BHrs':7,'NBHrs':1},]



def write_to_csv(filename, list_hours):
  '''
  INPUT Param 1: filename to write the csv file example, hours_06162020_150623.csv(filename_MMDDYYYY_HHMMSS.csv)
  INPUT Param 2: List_hours has collection of dictionaries in a list each dictionary include name,hours(billable + non-billable hours),billable hours,non-billable hours
  OUTPUT: A csv file is written thru dictionary of lists in the given directory/.
  '''
    #Initial Assigment to zero
    total_Hrs = total_BHrs = total_NBHrs = 0.0
    # Assign new ordered dict to store the order in which dictionary is inserted.
    new_dict = OrderedDict()
    
    #open a csv file with write mode and newline is null
    with open(filename, 'w', newline='') as file:
        #write the csv file start
        writer = csv.writer(file)
        
        #write the column heading for the first row.
        writer.writerow(["Name", "Hours", "Billable Hours", "Non Billable Hours"])
        
        #accumulate hours of all the rows.
        for item in list_hours:
            total_Hrs += item['Hrs']
            total_BHrs += item['BHrs']
            total_NBHrs += item['NBHrs']
        
        #assign the hours to new dictionary
        new_dict['Name'] = "Total"
        new_dict['Hrs'] = total_Hrs
        new_dict['BHrs'] = total_BHrs
        new_dict['NBHrs']= total_NBHrs
        
        #append to existing list_hours.
        list_hours.append(new_dict)
        
        for item in list_hours:
             #write each row to the csv
             writer.writerow([item['Name'], item['Hrs'], item['BHrs'], item['NBHrs']])
0
input_file = csv.DictReader(open("coors.csv"))
0

New to Communities?

Join the community