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