Fermi paradox SO Fermi paradox SO - 2 years ago 61
Python Question

write() file by inserting dict in specific key order and format

I need to create a file, and insert a dictionary in it.
The dictionary has to:

  • be in a format like

  • have keys ordered in a specific way.

I know i can simply use
with open()
and insert everything in a specific order with some custom-made function...

with open('Dog.txt', 'w') as opened_file:
str_to_write = ''
for key, val in my_order_function(my_dct):
# Create the string with keys in order i need.
str_to_write += ....


but i was wondering if there is a way to achieve both ordering and format with some already existing builtins.

Answer Source

Probably the closest short of looping and building a string, is something using pprint.pformat, such as:

>>> from pprint import pformat
>>> my_dct = dict(
>>> print('my_dct = {{\n {}\n}}'.format(pformat(my_dct, width=1)[1:-1]))
my_dct = {
 'k1': 1,
 'k2': 2,
 'k3': 3
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download