DEV Community

Discussion on: 30 PyTricks I've Learned By Joining the Real Python Mailing List.

Collapse
 
geraldew profile image
geraldew

By coincidence I recently encountered the reason why item 7 "Pretty print a dict." is not reliable.
i.e. Answer: Using json.dumps method.

This will fail when the items in the dictionary are not things that can be expressed as JSON. The two I encountered were enumerations and tuples.

Collapse
 
gdledsan profile image
Edmundo Sanchez

There is a library to solve that, check orjson, its faster, it parses more types, check it out

Collapse
 
wiseai profile image
Mahmoud Harmouch

Actually, I don't like to use this method, but rather engineer my own thing. For instance, at some point in the past, i created these handy functions:

def indent(string: str, num_spaces: int) -> str:
    indent_str: str = " " * num_spaces
    return "\n".join(indent_str + line for line in string.split("\n")[:-1]) + "\n"

def pretty_dict(dict_: dict[str, str], num_spaces: int) -> str:
  if not isinstance(dict_, dict):
    return repr(dict_)
  rep = []
  for key, val in dict_.items():
    rep.append(f"{key}: {pretty_dict(val, num_spaces)},\n")
  if rep:
    return f'{{\n{indent("".join(rep), num_spaces)}}}'
  else:
    return "{}"
Enter fullscreen mode Exit fullscreen mode

Usage:

>>> dict1 = {'b': 2, 'a': {'b': [1, 2, 3]}, 'c': list(enumerate(range(4)))}
>>> print(pretty_dict(dict1, 2))
{
  b: 2,
  a: {
    b: [1, 2, 3],
  },
  c: [(0, 0), (1, 1), (2, 2), (3, 3)],
}
Enter fullscreen mode Exit fullscreen mode

It seems like, over the years, I developed a hate relationship with the DRY principle. Anyways, I hope you find it useful. Cheers mate!

Collapse
 
tompollard61 profile image
Tom Pollard

json.dumps() will represent tuples as JSON lists. But there are certainly other Python types that json.dumps() can't handle, like datetimes

The pprint ("pretty-print") module handles all of those. So, instead of json.dumps() you can use pprint.pprint()

Collapse
 
gdledsan profile image
Edmundo Sanchez

Check orjson, faster and better json handling

Collapse
 
geraldew profile image
geraldew

Well it simply didn't in the environment that I was using, instead it crashed on the tuple. To be clear, the tuple was being used as a key in the Python dictionary, something that Python allows but I'm guessing has no equivalence in JSON.

Thread Thread
 
tompollard61 profile image
Tom Pollard

Yes, JSON keys need to be strings.

In any case, pprint was introduced to the stdlib specifically to handle pretty-printing of Python values, but I don't run across many people who seem to know about it.

Thread Thread
 
geraldew profile image
geraldew

post script - as it happened I was curious enough about JSON versus data structures to try getting it to handle something more than just text keys. So I wrote an experiment about using enumerations - see: