Posts

Showing posts with the label dict

Google spreadsheet data to list using Google Apps Script

Here is the snippet I just wrote, pretty convenient:

Transposing csv data using Python

Here is the case: You have this original csv data: name,course,number A,Genius,12 A,Super,13 B,Goddess,15 C,The Man,17 C,The Woman,10 C,Harvard,11 C,StanFord,18 and you want to create another csv file that uses name 's values as columns and group the course 's value as rows: A,B,C Genius,Goddess,The Man Super,'',The Woman '','',Harvard '','',StanFord Here is what I did to achieve that: 1. Read the original csv file and convert it into a list of dicts 2. Transpose the list by grouping the name column: Get all the name's value group_cols = [] for o in original_list: if o[group_col_name].strip() not in group_cols: group_cols.append(o[group_col_name].strip()) For each of the name, loop through the original list and append the according course's value to a tmp list (with the name as the first item), then add all of the tmp lists to a new list: thelist = [] for c in group_co...

Python - Write dictionary data to csv file

Image
Assuming I have a list of dictionaries called mydict: mydict = [{'name': 'Trinh Nguyen', 'value': 'Super Genius'}, {'name':'God', 'value': 'Cool'},...] and I want to write that list to a csv file, so I write the following reusable python function: import csv def write_dict_data_to_csv_file(csv_file_path, dict_data):     csv_file = open(csv_file_path, 'wb')     writer = csv.writer(csv_file, dialect='excel')         headers = dict_data[0].keys()     writer.writerow(headers)     for dat in dict_data:         line = []         for field in headers:             line.append(dat[field])         writer.writerow(line)             csv_file.close() write_dict_data_to_csv_file('mycsv.csv', mydict)

Python - Get dictionary data from csv file

Image
Read the csv file, and put the data into a dictionary: #!/usr/bin/python import csv def csv_to_dict(csv_file_path):     csv_file = open(csv_file_path, 'rb')     csv_file.seek(0)     sniffdialect = csv.Sniffer().sniff(csv_file.read(10000), delimiters='\t,;')     csv_file.seek(0)     dict_reader = csv.DictReader(csv_file, dialect=sniffdialect)     csv_file.seek(0)     dict_data = []     for record in dict_reader:         dict_data.append(record)     csv_file.close()     return dict_data