Lisien Semanjaku
Lisien Semanjaku

Reputation: 23

How can I have the tkintertable table's columns sorted the way they are in the dictionary?

I am working with python 2.7 64bit on Windows (using Pycharm) and want to display some data in a table for a project of mine. I tried using pandastable at first but gave up since it searches for the names python 3. has for tkinter. My problem is that, given the dictionary with the data to import for example:

data={'1': {'Klasa':'6A', 'E Hene': 1, 'E Marte': 2,'E Merkurre':3,'E Enjte':4,'E Premte':5},
      '2': {'Klasa':'', 'E Hene': 1, 'E Marte': 2,'E Merkurre':3,'E Enjte':4,'E Premte':5}}

I expected that the columns names were sorted the same order they are in the dictionary but that is not the case. They are actually sorted:

'E Enjte', 'Klasa', 'E Premte', 'E Merkurre', 'E Hene', 'E Marte'

from left to right. Below is the code I was testing.

from Tkinter import *
from tkintertable.Tables import TableCanvas
from tkintertable.TableModels import TableModel
master=Tk()
tframe = Frame(master)
tframe.pack(fill='both')
data={'1': {'Klasa':'6A', 'E Hene': 1, 'E Marte': 2,'E Merkurre':3,'E Enjte':4,'E Premte':5},
      '2': {'Klasa':'', 'E Hene': 1, 'E Marte': 2,'E Merkurre':3,'E Enjte':4,'E Premte':5}}
model = TableModel()
table = TableCanvas(tframe,model=model)
table.createTableFrame()
model = table.model
model.importDict(data) #can import from a dictionary to populate model
master.mainloop()

Upvotes: 2

Views: 1103

Answers (1)

ohmu
ohmu

Reputation: 19761

There are two ways you can do this.

1. Use a predefined column order.

Right before model.importDict(data), you should define the columns on model:

columns = ['Klasa', 'E Hene', 'E Marte', 'E Merkurre', 'E Enjte', 'E Premte']
for column in columns:
    model.addColumn(column)

2. Use OrderedDict.

Wherever your data comes from (e.g., a CSV or database), you should make your row dictionaries using collections.OrderedDict:

import collections

data = {'1': collections.OrderedDict([('Klasa', '6A'), ('E Hene', 1), ('E Marte', 2), ('E Merkurre', 3), ('E Enjte', 4), ('E Premte', 5)]),
        '2': collections.OrderedDict([('Klasa', ''), ('E Hene', 1), ('E Marte', 2), ('E Merkurre', 3), ('E Enjte', 4), ('E Premte', 5)])}

Upvotes: 1

Related Questions