Hi @zadstofun welcome to the forum!
You don’t need to use pandas or numpy to do this, but you do need some way to map your dictionary keys to numeric values – Qt’s models work on rows and columns.
What I would do is define a list of header values and/or dictionary keys. Then you can use the column index to get your key, and use this to get the data from the dictionary. For example –
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
class DictionaryTableModel(QtCore.QAbstractTableModel):
def __init__(self, data, headers):
super(DictionaryTableModel, self).__init__()
self._data = data
self._headers = headers
def data(self, index, role):
if role == Qt.DisplayRole:
# Look up the key by header index.
column = index.column()
column_key = self._headers[column]
return self._data[index.row()][column_key]
def rowCount(self, index):
# The length of the outer list.
return len(self._data)
def columnCount(self, index):
# The length of our headers.
return len(self._headers)
def headerData(self, section, orientation, role):
# section is the index of the column/row.
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
return str(self._headers[section])
if orientation == Qt.Vertical:
return str(section)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.table = QtWidgets.QTableView()
data = [
{'a':4, 'b':9, 'c':2},
{'a':1, 'b':0, 'c':0},
{'a':3, 'b':5, 'c':0},
{'a':3, 'b':3, 'c':2},
{'a':7, 'b':8, 'c':9},
]
headers = ['a', 'b', 'c']
self.model = DictionaryTableModel(data, headers)
self.table.setModel(self.model)
self.setCentralWidget(self.table)
app=QtWidgets.QApplication(sys.argv)
window=MainWindow()
window.show()
app.exec_()
If you want to show different headers to your keys you can - just create a separate list (e.g. _keys) and perform the data lookup on that instead.