0

I have a dictionary that looks like this

{'Berlin': {'Type1': 96},
 'Frankfurt': {'Type1': 48},
 'London': {'Type1': 288, 'Type2': 64, 'Type3': 426},
 'Paris': {'Type1': 48, 'Type2': 96}}

I then want to write to a .txt file in the format

London
  Type1: 288
  Type2: 64
  Type3: 426

Paris
  Type1: 48
  Type2: 96

Frankfurt
  Type1: 48

Berlin
  Type1: 98

I've tried to use

f = open("C:\\Users\\me\\Desktop\\capacity_report.txt", "w+")
f.write(json.dumps(mydict, indent=4, sort_keys=True))

but this prints like this:

{
    "London": {
        "Type1": 288,
        "Type2": 64,
        "Type3": 426
     },
     "Paris": {
         "Type1": 48,
         "Type2": 96
     },
     "Frankfurt": {
         "Type1": 48
      },
      "Berlin": {
         "Type1": 98
      }
}

I'd like to have the punctuation and brackets removed. Is there a way to do this I can't see?

martineau
  • 119,623
  • 25
  • 170
  • 301
CEamonn
  • 853
  • 14
  • 37

2 Answers2

2

You'll need to write out your dictionary manually. You are not trying to produce JSON here, and there is no point in using that module.

Iterate over the dictionary keys and values and write those out as lines. The print() function can be helpful here:

from __future__ import print_function

with open("C:\\Users\\me\\Desktop\\capacity_report.txt", "w") as f:
    for key, nested in sorted(mydict.items()):
        print(key, file=f)
        for subkey, value in sorted(nested.items()):
            print('   {}: {}'.format(subkey, value), file=f)
        print(file=f)

The print() function takes care of newlines for us.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

If you use python 3.6 which preserve order on insert keys on dictionary, you can use something like this.

with open('filename.txt','w') as f:
    for city, values in my_dict.items():
        f.write(city + '\n')
        f.write("\n".join(["  {}: {}".format(value_key, digit) for value_key, digit in values.items()]) + '\n')
        f.write('\n')

Its works changing f.write for print. i hope this helps.

Tzomas
  • 704
  • 5
  • 17