diff --git a/index.md b/index.md index ae4de7f..711eee4 100644 --- a/index.md +++ b/index.md @@ -325,6 +325,10 @@ This file gets generated by [this script](index.py). - [Make a terminal plot](notes/20240119105430.md) +## Pprint + +- [Pretty print to a file](notes/20240529114443.md) + ## Property - [Computed (and readonly) fields / attributes](notes/20230829122437.md) diff --git a/notes/20240529114443.md b/notes/20240529114443.md new file mode 100644 index 0000000..8d9b571 --- /dev/null +++ b/notes/20240529114443.md @@ -0,0 +1,21 @@ +# pretty print to a file + +I was in the Python debugger today and I was wondering how to write a sorted dictionary to a file while there. 💪 + +And then I learned that pprint's `PrettyPrinter` can stream to a file, nice! 😎 + +Here is how: + +``` +import pprint + +# sort by numeric value descending (here: most listened podcast episodes) +sorted_stats = sorted(stats.items(), key=lambda x: x[1], reverse=True) + +# pretty print the dict to a text file +with open('sorted_stats.txt', 'w') as file: + pp = pprint.PrettyPrinter(stream=file, indent=4) + pp.pprint(sorted_stats) +``` + +#pprint