Search code examples
pythonformatpprint

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 pprint().
  • 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 += ....

    opened_file.write(str_to_write)

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


Solution

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

    >>> from pprint import pformat
    >>> my_dct = dict(
        k1=1,
        k3=3,
        k2=2,)
    >>> print('my_dct = {{\n {}\n}}'.format(pformat(my_dct, width=1)[1:-1]))
    my_dct = {
     'k1': 1,
     'k2': 2,
     'k3': 3
    }