Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1#!/usr/local/bin/python
2# encoding: utf-8
3"""
4*Convert a python list of dictionaries to pretty csv output*
6:Author:
7 David Young
8"""
9import sys
10import os
11import io
12import csv
13from decimal import Decimal
14from datetime import datetime
15os.environ['TERM'] = 'vt100'
16from fundamentals import tools
17from fundamentals.mysql import convert_dictionary_to_mysql_table
19def list_of_dictionaries_to_mysql_inserts(
20 log,
21 datalist,
22 tableName):
23 """Convert a python list of dictionaries to pretty csv output
25 **Key Arguments**
27 - ``log`` -- logger
28 - ``datalist`` -- a list of dictionaries
29 - ``tableName`` -- the name of the table to create the insert statements for
32 **Return**
34 - ``output`` -- the mysql insert statements (as a string)
37 **Usage**
39 ```python
40 from fundamentals.files import list_of_dictionaries_to_mysql_inserts
41 mysqlInserts = list_of_dictionaries_to_mysql_inserts(
42 log=log,
43 datalist=dataList,
44 tableName="my_new_table"
45 )
46 print mysqlInserts
47 ```
49 this output the following:
51 ```plain
52 INSERT INTO `testing_table` (a_newKey,and_another,dateCreated,uniqueKey2,uniquekey1) VALUES ("cool" ,"super cool" ,"2016-09-14T13:17:26" ,"burgers" ,"cheese") ON DUPLICATE KEY UPDATE a_newKey="cool", and_another="super cool", dateCreated="2016-09-14T13:17:26", uniqueKey2="burgers", uniquekey1="cheese" ;
53 ...
54 ...
55 ```
57 """
58 log.debug('starting the ``list_of_dictionaries_to_mysql_inserts`` function')
60 if not len(datalist):
61 return "NO MATCH"
63 inserts = []
65 for d in datalist:
66 insertCommand = convert_dictionary_to_mysql_table(
67 log=log,
68 dictionary=d,
69 dbTableName="testing_table",
70 uniqueKeyList=[],
71 dateModified=False,
72 returnInsertOnly=True,
73 replace=True,
74 batchInserts=False
75 )
76 inserts.append(insertCommand)
78 output = ";\n".join(inserts) + ";"
80 log.debug('completed the ``list_of_dictionaries_to_mysql_inserts`` function')
81 return output