November 2017

Python: how to save a dictionary with objects to JSON

Each object’s class to be stored in JSON in a convenient for viewing way must have the __repr__ function, which returns the text representation of the object.

The dictionary with objects:

Saving the dictionary to JSON:

 

Python: how to enclose a tuple in a tuple

Tuples in python can be nested.

If simply add one tuple to another through the concatenation operation “+”, python will merge the values of the tuples:

In order an added tuple to become nested, put a comma “,” after an added tuple:

 

Python: How to find the polygon center coordinates

Obtaining the “centroid” – convex polygon central point coordinates, from polygons points (vertices) coordinates:

The input function parameter is a tuple with coordinates of the polygon points. The function returns a tuple with the centroid coordinates: