- Notifications
You must be signed in to change notification settings - Fork 0
py snippets misc
holzkohlengrill edited this page Dec 15, 2023 · 2 revisions
Snippets that do not fit into another category or are to small worth creating an own page for it.
Converts a dictionary (for example previously dumped and loaded from a JSON file) to a corresponding class (like a struct)
def __Dict2Class__(dict) : """ Converts a dictionary to a corresponding class (like a struct) :param dict: dictionary (tree) :return: class """ class classInit : def __init__(self, dict): for name, val in dict.items() : setattr(self, name, val) return classInit(dict) def _dict2class(self): class classInit: def __init__(self, dict): for name, val in dict.items(): setattr(self, name, val) return classInit(dict)python -m json.tool json-input-file-to-pretty-print.json Creates for outputs like: prefix--2017-04-20_-_17h35m11_-_alphabeticallySorted.csv
import datetime import csv prefix = "prefix" postfix = "alphabeticallySorted" currentDateTime = datetime.datetime.now().strftime("%Y-%m-%d_-_%Hh%Mm%S") extension = ".csv" if postfix != "": postfix = "_-_" + postfix if prefix != "": prefix = prefix + "_-_" filename = prefix + currentDateTime + postfix + extension with open(filename, "w") as fp: # Creates f.e.x.: `prefix_-_2017-04-20_-_17h35m11_-_alphabeticallySorted.csv` # Do something with it passPrints nested lists as nice tree plot.
testInput = ['a', 'a', 'a', ['b', 'b', 'b', 'b'], 'a', ['b', ['c', ['d', ['e'] ] ] ] ]Tree plot class:
class TreePlot: """ usage: >>> TreePlot(nestedListsOfLists) --> plots tree of `nestedListsOfLists`s structure """ depth = int(0) def __init__(self, inputList): self._plot(inputList) def _plot(self, inputList): for item in inputList: if isinstance(item, list): self.depth += 1 self._plot(item) #self._plot(item) else: print("".rjust(self.depth + 1, '+'), "-", item) self.depth -= 1
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License *.
Code (snippets) are licensed under a MIT License *.
* Unless stated otherwise