遍历字典并将数据放置在PyQt5表中

时间:2018-12-04 14:31:01

标签: python dictionary pyqt5

我有一本具有以下结构的字典。

 self.data = [{'username':'Homer', 'address':'11.11.111.111'}, {'username':'Bart', 'address':'22.22.222.222'}]

我想做的是在PyQt5中的表中显示此数据。我试图做的是如下所示:

    for rowIndex, username in enumerate(self.data["username"]["address"]):
        itemName = QTableWidgetItem(username["name"])  # fills cell with material name
        itemName.setFlags(QtCore.Qt.ItemIsEnabled)  # makes cell read only
        itemAddress = QTableWidgetItem()  # creates widget for cell
        itemAddress.setData(username["address"])  # fills material amount and makes it editable

        self.tableWidget.setItem(rowIndex, 0, itemName)  # positioning cell
        self.tableWidget.setItem(rowIndex, 1, itemAddress)  # positioning cell

这样做,我得到以下错误:

TypeError: list indices must be integers or slices, not str

这是可以理解的,因为它是字符串格式,如何显示下表所示的数据?

|---------------------|------------------|
|      username       |     address      |
|---------------------|------------------|
|     test user       |  11.111.111.111  |
|---------------------|------------------|

任何帮助将不胜感激!谢谢!

2 个答案:

答案 0 :(得分:1)

您有一个列表,而不是字典。 [dict, dict, dict]list中的dicts。这意味着您可以像这样访问它:

self.data[0] # Get the zeroth dict in list

或者像这样遍历它:

new_data = [x[key][sub_key] for x in self.data] # All must be dict-like in this list

或者list可以执行的其他任何操作,但dict不能执行。

错误是:

enumerate(self.data["username"]["address"])

具体来说:["username"],当期望int通过list访问[]

答案 1 :(得分:1)

这里的键是self.data是列表,而不是字典;因此self.data["username"]是错误的。这是建议的解决方法:

    for rowIndex, record in enumerate(self.data):
        itemName = QTableWidgetItem(record['username'])
        itemAddress = QTableWidgetItem(record['address'])
        # more ...