2

I am trying to write from Python into an Excel workbook using XlsxWriter. I have a dictionary called Pg whose keys are tuples.

for key,value in Pg.iteritems():
     for t in range(1,4):
      if key==(0,t):
       worksheet.write(row,col,value.x)
       row += 1

I want to write values of key (0,t) in a column, but the values don't appear in normal order. For example, if my dictionary looks like this:

Pg={(0,1):1,(0,2):2,(0,3):3}

I get in Excel:

1
3
2

Why is this happening when I have strictly determined in the second for loop how I want my values to be written?

John Y
  • 14,123
  • 2
  • 48
  • 72
  • Answers here. [http://stackoverflow.com/questions/13437727/python-write-to-excel-spreadsheet](http://stackoverflow.com/questions/13437727/python-write-to-excel-spreadsheet) – voidpro Apr 21 '17 at 13:03
  • Possible duplicate of [Python - Write to Excel Spreadsheet](http://stackoverflow.com/questions/13437727/python-write-to-excel-spreadsheet) – user2263572 Apr 21 '17 at 13:14
  • This question isn't a duplicate of the linked question. I've revised the subject line to more accurately reflect the thrust of this question. (It is very likely a duplicate of, or at least related to, *other* questions about Python dictionaries and how to order them. Simply writing to Excel is not the main issue here.) – John Y Apr 21 '17 at 21:21

1 Answers1

3

I think you realize that when you iterate over a dictionary, you are not guaranteed any specific ordering. The problem you are having is that the way you are trying to force an ordering is flawed.

for key,value in Pg.iteritems():
    for t in range(1,4):
        if key==(0,t):
            # ...

What this does is iterate over each key, value pair first. Then inside this you output if the key matches a certain condition. If you switched the ordering of the for loops, you would get what you wanted, but this method is not efficient at all.

More simply, you can iterate over the sorted dictionary like this:

for key, value in sorted(Pg.iteritems()):
    worksheet.write(row, col, value.x)
    row += 1
msitt
  • 1,237
  • 12
  • 27