Python offers a handy [pprint](https://docs.python.org/3/library/pprint.html) module, which has helpers for formatting and printing data in a nicely-formatted way.
One under-appreciated method is [pprint.saferepr()](https://docs.python.org/3/library/pprint.html#pprint.saferepr), which advertises itself as returning a string representation of an object that is safe in the case of:
```python
d = {'key': 'value'}
d['d'] = d
```
`saferepr()` won't recurse infinitely, and this can be good for some classes of input.
## But wait, there's more!
This doesn't just handle recursion. It also sorts keys in dictionaries. This is _really_ handy when writing unit tests that need to compare, say, logging of data.
Modern versions of Python 3 will preserve insertion order of keys into dictionaries, which can be nice but aren't always great for comparison purposes.
For example:
```python
>>> d = {}
>>> d['z'] = 1
>>> d['a'] = 2
>>> d['g'] = 3
>>>
>>> repr(d)
"{'z': 1, 'a': 2, 'g': 3}"
>>>
>>> from pprint import saferepr
>>> saferepr(d)
"{'a': 2, 'g': 3, 'z': 1}"
```
A useful tool to have in your toolbelt.