1

I need to save some information of my data to the text file before saving the data matrix, but I found that the order is a little different from that I initially assigned to the dictionary. How can I keep the correct order? Here is my code:

headers = {}
headers["ncols"] = "184"
headers["nrows"] = "223"
headers["xllcorner"] = "0"
headers["yllcorner"] = "0"
headers["cellsize"] = "1000"
headers["NODATA_value"] = "-9999"
path = "DATA.txt"
with open(path, 'w') as f:
    for K, V in headerdict.items():
        f.write(K + "\t" + V + "\n")

This is the resulting file I get: Resulting text file I get:

PS: Python 2.7

Community
  • 1
  • 1
KarlHuang
  • 111
  • 1
  • 1
  • 8

2 Answers2

0

You need to use ordereddict

from collections import OrderedDict

headers = OrderedDict()

headers = {}
headers["ncols"] = "184"
headers["nrows"] = "223"
headers["xllcorner"] = "0"
headers["yllcorner"] = "0"
headers["cellsize"] = "1000"
headers["NODATA_value"] = "-9999"

with open(r"D:\data\desktop-jul12016\Desktop This Week\demo.txt", 'w') as f:
    for K, V in headers.items():
        f.write(K + "\t" + V + "\n")
Rahul
  • 10,830
  • 4
  • 53
  • 88
0

You can use OrderedDict data structure from collections module.

you can read more about it here

Yaman Jain
  • 1,254
  • 11
  • 16