-4

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.

user
  • 5,370
  • 8
  • 47
  • 75
  • You can start with `pprint.pformat(my_dct, width=1)` - but you'll get a `dict` literal intstead... You'll have to add the `my_dct = ` whatever yourself, but if you want to keep it as a `dict(...)`, or otherwise reformat it, you'll just have to build a string looping over the keys as appropriate. Is that the sort of thing you're after? – Jon Clements Jan 25 '15 at 21:04
  • @JonClements I was wondering if there is a better way to insert `my_dict= `. Otherwise i ll use `pformat` and a string looping. Thanks for that. – user Jan 25 '15 at 21:13

1 Answers1

2

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
}
Jon Clements
  • 138,671
  • 33
  • 247
  • 280