-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
e9ee187
commit 3ac8354
Showing
2 changed files
with
25 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |