Skip to content

Instantly share code, notes, and snippets.

@mccbryan3
Last active July 4, 2021 01:26
Show Gist options
  • Select an option

  • Save mccbryan3/2da20edbd784d87b526af099d6666b9c to your computer and use it in GitHub Desktop.

Select an option

Save mccbryan3/2da20edbd784d87b526af099d6666b9c to your computer and use it in GitHub Desktop.
'''
Class: UniformKeys
Class Summary: This Class is used to make key values
uniform and requires a list of dictionaries
Author: Bryan McClellan
Created: 6/22/2021
'''
import logging as log
import csv
import sys
import json
from tabulate import tabulate
class UniformKeys:
def __init__(self, data: list):
""" Initiallize object from class"""
self._data = data
if type(self._data[0]) != dict:
log.warning("Data is not a list of dictionaries")
sys.exit()
def get_headers(self):
""" Create a full list of the unique headers """
new_dict = {}
for d in self._data:
new_dict.update(d)
return list(new_dict.keys())
def get_uniform_data(self):
""" Creates list of dict with unform keys for each instance """
my_list = []
headers = self.get_headers()
for d in self._data:
entry_dict = dict.fromkeys(headers)
entry_dict.update(d)
my_list.append(entry_dict)
return_list = my_list[:]
return return_list
def output_csv(self, csv_file: str):
""" Prints the uniform data to csv"""
try:
with open(csv_file, "w", newline='') as f:
writer = csv.DictWriter(f, fieldnames=self.get_headers())
writer.writeheader()
writer.writerows(self.get_uniform_data())
except IOError as e:
log.warning("Eror writing to file: {}".format(e))
finally:
f.close()
def output_json(self):
""" Return output as indented json """
json_output = json.dumps(self.get_uniform_data(), indent=4)
return json_output
def print_table(self):
""" Print table of data using tabulate """
table = []
for values in self.get_uniform_data():
table.append(list(values.values()))
print(tabulate(table, headers=self.get_headers()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment