Skip to content

py snippets misc

holzkohlengrill edited this page Dec 15, 2023 · 2 revisions

Random python snippet collection

Snippets that do not fit into another category or are to small worth creating an own page for it.

Dict 2 class

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)

Pretty-print JSON using python

python -m json.tool json-input-file-to-pretty-print.json 

Write file with unique timestamp (template)

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
    pass

Tree plot

Prints 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
Clone this wiki locally