Member-only story
Python tricks and treats
In this article I am going to present four useful python tricks that you can use to enhance your programming skills and maybe show off to your fellow colleagues.
Dictionary printing
Due to its fast data access a dictionary can be useful in countless scenarios and sometimes we might want to see its whole content, of course we will quickly go to our precious “print” function. While this will certainly work and show us what we want it will not show it in the most readable way.
An alternative to “print” is to use json.dump
or pprint.pprint
, both have their ups and downs but are a much better solution. Let’s look to each one and see how they behave:
- For
json.dump
as you can see in the example below we get a nice, indented string representation of our dictionary. The problem is that it only works with json compatible data types, so when it encounters a more complex data type like a set, it will throw a type error.
>>> import json
>>> json.dumps(cats_dict, indent=4, sort_keys=True)
{
"cat_1": "small cat",
"cat_2": "big cat",
"cat_3": "angry cat"
}
- Using
pprint
allows us to view even more complex data structures and the elements are shown in a deterministic order, the problem is that it can have problems with nested structures: