How to create a dictionary from QtableWidgetItem?How to merge two dictionaries in a single expression?How do I efficiently iterate over each entry in a Java Map?How do I sort a list of dictionaries by a value of the dictionary?What is the best way to iterate over a dictionary?How do I sort a dictionary by value?Add new keys to a dictionary?Check if a given key already exists in a dictionaryCreate a dictionary with list comprehension in PythonIterating over dictionaries using 'for' loopsHow to remove a key from a Python dictionary?
Failing students when it might cause them economic ruin
Good examples of "two is easy, three is hard" in computational sciences
on the truth quest vs in the quest for truth
Why do academics prefer Mac/Linux?
Why does a table with a defined constant in its index compute 10X slower?
Why are there five extra turns in tournament Magic?
Why does Taylor’s series “work”?
Driving a school bus in the USA
How to get all possible paths in 0/1 matrix better way?
Should all adjustments be random effects in a mixed linear effect?
How to draw pentagram-like shape in Latex?
How was the blinking terminal cursor invented?
How can sister protect herself from impulse purchases with a credit card?
Is my company merging branches wrong?
how to create an executable file for an AppleScript?
How do we explain the use of a software on a math paper?
How does this piece of code determine array size without using sizeof( )?
Gambler's Fallacy Dice
Save my secrets!
What were the "pills" that were added to solid waste in Apollo 7?
Taylor series leads to two different functions - why?
Was murdering a slave illegal in American slavery, and if so, what punishments were given for it?
Why didn't Daenerys' advisers suggest assassinating Cersei?
pwaS eht tirsf dna tasl setterl fo hace dorw
How to create a dictionary from QtableWidgetItem?
How to merge two dictionaries in a single expression?How do I efficiently iterate over each entry in a Java Map?How do I sort a list of dictionaries by a value of the dictionary?What is the best way to iterate over a dictionary?How do I sort a dictionary by value?Add new keys to a dictionary?Check if a given key already exists in a dictionaryCreate a dictionary with list comprehension in PythonIterating over dictionaries using 'for' loopsHow to remove a key from a Python dictionary?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
i'm retrieving my data from a CSV file into a QtableWidget, i created some methods to modify, delete, insert column and rows even new items... in the QtableWidget, so before going to the next step i need to convert the current QtableWidgetItem into a dictionary.( Not the data from the file!) by pressing a button .
class MyWindow(QMainWindow):
def __init__(self, *args, parent=None):
super(MyWindow, self).__init__(parent)
self.fileName = ""
self.result =
##### Event for the button
self.ui.commandLinkButton.clicked.connect(self.generateCsvData)
def loadCsvOnOpen(self, fileName): #Load CSV file
if fileName:
f = open(fileName, 'r')
mystring = f.read()
if mystring.count(",") > mystring.count('t'):
if mystring.count(",") > mystring.count(';') :
self.delimit = ","
elif mystring.count(";") > mystring.count(',') :
self.delimit = ";"
else:
self.delimit = "t"
elif mystring.count(";") > mystring.count('t'):
self.delimit = ';'
else:
self.delimit = "t"
f.close()
f = open(fileName, 'r')
self.ui.tableView.setRowCount(0)
self.ui.tableView.setColumnCount(0)
for rowdata in csv.reader(f, delimiter=self.delimit):
row = self.ui.tableView.rowCount()
self.ui.tableView.insertRow(row)
if len(rowdata) == 0:
self.ui.tableView.setColumnCount(len(rowdata) + 1)
else:
self.ui.tableView.setColumnCount(len(rowdata))
for column, data in enumerate(rowdata):
item = QTableWidgetItem(data)
self.ui.tableView.setItem(row, column, item)
self.ui.tableView.selectRow(0)
self.isChanged = False
self.setCurrentFile(fileName)
self.ui.tableView.resizeColumnsToContents()
self.ui.tableView.resizeRowsToContents()
self.msg(fileName + " loaded")
def generateCsvData(self):
for row in range(self.ui.tableView.rowCount()):
for column in range(self.ui.tableView.columnCount()):
item = self.ui.tableView.item(row, column)
if item is not None:
self.result[row[0]] = (row[1:])
print(self.result)
else:
return
python-3.x dictionary pyqt5 qtablewidget qtablewidgetitem
add a comment |
i'm retrieving my data from a CSV file into a QtableWidget, i created some methods to modify, delete, insert column and rows even new items... in the QtableWidget, so before going to the next step i need to convert the current QtableWidgetItem into a dictionary.( Not the data from the file!) by pressing a button .
class MyWindow(QMainWindow):
def __init__(self, *args, parent=None):
super(MyWindow, self).__init__(parent)
self.fileName = ""
self.result =
##### Event for the button
self.ui.commandLinkButton.clicked.connect(self.generateCsvData)
def loadCsvOnOpen(self, fileName): #Load CSV file
if fileName:
f = open(fileName, 'r')
mystring = f.read()
if mystring.count(",") > mystring.count('t'):
if mystring.count(",") > mystring.count(';') :
self.delimit = ","
elif mystring.count(";") > mystring.count(',') :
self.delimit = ";"
else:
self.delimit = "t"
elif mystring.count(";") > mystring.count('t'):
self.delimit = ';'
else:
self.delimit = "t"
f.close()
f = open(fileName, 'r')
self.ui.tableView.setRowCount(0)
self.ui.tableView.setColumnCount(0)
for rowdata in csv.reader(f, delimiter=self.delimit):
row = self.ui.tableView.rowCount()
self.ui.tableView.insertRow(row)
if len(rowdata) == 0:
self.ui.tableView.setColumnCount(len(rowdata) + 1)
else:
self.ui.tableView.setColumnCount(len(rowdata))
for column, data in enumerate(rowdata):
item = QTableWidgetItem(data)
self.ui.tableView.setItem(row, column, item)
self.ui.tableView.selectRow(0)
self.isChanged = False
self.setCurrentFile(fileName)
self.ui.tableView.resizeColumnsToContents()
self.ui.tableView.resizeRowsToContents()
self.msg(fileName + " loaded")
def generateCsvData(self):
for row in range(self.ui.tableView.rowCount()):
for column in range(self.ui.tableView.columnCount()):
item = self.ui.tableView.item(row, column)
if item is not None:
self.result[row[0]] = (row[1:])
print(self.result)
else:
return
python-3.x dictionary pyqt5 qtablewidget qtablewidgetitem
add a comment |
i'm retrieving my data from a CSV file into a QtableWidget, i created some methods to modify, delete, insert column and rows even new items... in the QtableWidget, so before going to the next step i need to convert the current QtableWidgetItem into a dictionary.( Not the data from the file!) by pressing a button .
class MyWindow(QMainWindow):
def __init__(self, *args, parent=None):
super(MyWindow, self).__init__(parent)
self.fileName = ""
self.result =
##### Event for the button
self.ui.commandLinkButton.clicked.connect(self.generateCsvData)
def loadCsvOnOpen(self, fileName): #Load CSV file
if fileName:
f = open(fileName, 'r')
mystring = f.read()
if mystring.count(",") > mystring.count('t'):
if mystring.count(",") > mystring.count(';') :
self.delimit = ","
elif mystring.count(";") > mystring.count(',') :
self.delimit = ";"
else:
self.delimit = "t"
elif mystring.count(";") > mystring.count('t'):
self.delimit = ';'
else:
self.delimit = "t"
f.close()
f = open(fileName, 'r')
self.ui.tableView.setRowCount(0)
self.ui.tableView.setColumnCount(0)
for rowdata in csv.reader(f, delimiter=self.delimit):
row = self.ui.tableView.rowCount()
self.ui.tableView.insertRow(row)
if len(rowdata) == 0:
self.ui.tableView.setColumnCount(len(rowdata) + 1)
else:
self.ui.tableView.setColumnCount(len(rowdata))
for column, data in enumerate(rowdata):
item = QTableWidgetItem(data)
self.ui.tableView.setItem(row, column, item)
self.ui.tableView.selectRow(0)
self.isChanged = False
self.setCurrentFile(fileName)
self.ui.tableView.resizeColumnsToContents()
self.ui.tableView.resizeRowsToContents()
self.msg(fileName + " loaded")
def generateCsvData(self):
for row in range(self.ui.tableView.rowCount()):
for column in range(self.ui.tableView.columnCount()):
item = self.ui.tableView.item(row, column)
if item is not None:
self.result[row[0]] = (row[1:])
print(self.result)
else:
return
python-3.x dictionary pyqt5 qtablewidget qtablewidgetitem
i'm retrieving my data from a CSV file into a QtableWidget, i created some methods to modify, delete, insert column and rows even new items... in the QtableWidget, so before going to the next step i need to convert the current QtableWidgetItem into a dictionary.( Not the data from the file!) by pressing a button .
class MyWindow(QMainWindow):
def __init__(self, *args, parent=None):
super(MyWindow, self).__init__(parent)
self.fileName = ""
self.result =
##### Event for the button
self.ui.commandLinkButton.clicked.connect(self.generateCsvData)
def loadCsvOnOpen(self, fileName): #Load CSV file
if fileName:
f = open(fileName, 'r')
mystring = f.read()
if mystring.count(",") > mystring.count('t'):
if mystring.count(",") > mystring.count(';') :
self.delimit = ","
elif mystring.count(";") > mystring.count(',') :
self.delimit = ";"
else:
self.delimit = "t"
elif mystring.count(";") > mystring.count('t'):
self.delimit = ';'
else:
self.delimit = "t"
f.close()
f = open(fileName, 'r')
self.ui.tableView.setRowCount(0)
self.ui.tableView.setColumnCount(0)
for rowdata in csv.reader(f, delimiter=self.delimit):
row = self.ui.tableView.rowCount()
self.ui.tableView.insertRow(row)
if len(rowdata) == 0:
self.ui.tableView.setColumnCount(len(rowdata) + 1)
else:
self.ui.tableView.setColumnCount(len(rowdata))
for column, data in enumerate(rowdata):
item = QTableWidgetItem(data)
self.ui.tableView.setItem(row, column, item)
self.ui.tableView.selectRow(0)
self.isChanged = False
self.setCurrentFile(fileName)
self.ui.tableView.resizeColumnsToContents()
self.ui.tableView.resizeRowsToContents()
self.msg(fileName + " loaded")
def generateCsvData(self):
for row in range(self.ui.tableView.rowCount()):
for column in range(self.ui.tableView.columnCount()):
item = self.ui.tableView.item(row, column)
if item is not None:
self.result[row[0]] = (row[1:])
print(self.result)
else:
return
python-3.x dictionary pyqt5 qtablewidget qtablewidgetitem
python-3.x dictionary pyqt5 qtablewidget qtablewidgetitem
edited Mar 23 at 20:59
Anass Belmaati
asked Mar 23 at 17:24
Anass BelmaatiAnass Belmaati
345
345
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
Try it:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Example(QDialog):
def __init__(self):
super().__init__()
self.tableWidget = QTableWidget()
self.result =
button = QPushButton("Create a dictionary from QtableWidgetItem")
button.clicked.connect(self.generateCsvData) # <---
self.layout = QVBoxLayout()
self.layout.addWidget(self.tableWidget)
self.layout.addWidget(button)
self.setLayout(self.layout)
self.tableWidget.setRowCount(4)
self.tableWidget.setColumnCount(2)
for i in range(4):
for j in range(2):
item = QTableWidgetItem("Item -".format(i, j))
item.setTextAlignment(Qt.AlignHCenter)
self.tableWidget.setItem(i, j, item)
def generateCsvData(self): # <---
for row in range(self.tableWidget.rowCount()):
for column in range(self.tableWidget.columnCount()):
item = self.tableWidget.item(row, column).text()
k = ":0>3::0>3".format(row, column)
v = "".format(item)
self.result[k] = v
print("n key value")
[ print(k, v) for k, v in self.result.items()]
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Example()
w.show()
sys.exit(app.exec_())
Update
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Example(QDialog):
def __init__(self):
super().__init__()
self.tableWidget = QTableWidget()
self.result =
button = QPushButton("Create a dictionary from QtableWidgetItem")
button.clicked.connect(self.generateCsvData) # <---
self.layout = QVBoxLayout()
self.layout.addWidget(self.tableWidget)
self.layout.addWidget(button)
self.setLayout(self.layout)
self.tableWidget.setRowCount(4)
self.tableWidget.setColumnCount(5)
for i in range(4):
for j in range(5):
if j == 0:
item = QTableWidgetItem("111".format(i))
else:
item = QTableWidgetItem("Item -".format(i, j))
item.setTextAlignment(Qt.AlignHCenter)
self.tableWidget.setItem(i, j, item)
def generateCsvData(self): # <---
for row in range(self.tableWidget.rowCount()):
v = []
for column in range(self.tableWidget.columnCount()):
if column == 0:
k = self.tableWidget.item(row, column).text()
else:
item = self.tableWidget.item(row, column).text()
v.append(item)
self.result[k] = v
print("n key value")
[ print(k, v) for k, v in self.result.items()]
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Example()
w.show()
sys.exit(app.exec_())
Thanks Bro, but i didn't mention that i need the dict with this fomrat: result = '1111':['Capital 1','145321','94565','','','','74651','','','24651','','',''], '1112':['Capital 2','65115','','6149','6645','555641','','','','41245','98416','',''], '1113':['Capital 3','544453','','45345453','','555641','434556','','453453','','98416','','453453'], ........., the key is an int and the value is a list if you remember from the previous questions
– Anass Belmaati
Mar 23 at 19:31
1
@AnassBelmaati Attach an image of what yourtableWidget
looks like with data
– S. Nick
Mar 23 at 19:44
i attached it bro check it
– Anass Belmaati
Mar 23 at 20:08
@AnassBelmaati see update
– S. Nick
Mar 23 at 21:09
1
When i added this instruction: self.result[v[0]] = (v[1:]) it's creating for every row a Dict and every time it append an item, use it to figure out what i'm talking about, and thank you.
– Anass Belmaati
Mar 23 at 21:37
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55316440%2fhow-to-create-a-dictionary-from-qtablewidgetitem%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Try it:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Example(QDialog):
def __init__(self):
super().__init__()
self.tableWidget = QTableWidget()
self.result =
button = QPushButton("Create a dictionary from QtableWidgetItem")
button.clicked.connect(self.generateCsvData) # <---
self.layout = QVBoxLayout()
self.layout.addWidget(self.tableWidget)
self.layout.addWidget(button)
self.setLayout(self.layout)
self.tableWidget.setRowCount(4)
self.tableWidget.setColumnCount(2)
for i in range(4):
for j in range(2):
item = QTableWidgetItem("Item -".format(i, j))
item.setTextAlignment(Qt.AlignHCenter)
self.tableWidget.setItem(i, j, item)
def generateCsvData(self): # <---
for row in range(self.tableWidget.rowCount()):
for column in range(self.tableWidget.columnCount()):
item = self.tableWidget.item(row, column).text()
k = ":0>3::0>3".format(row, column)
v = "".format(item)
self.result[k] = v
print("n key value")
[ print(k, v) for k, v in self.result.items()]
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Example()
w.show()
sys.exit(app.exec_())
Update
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Example(QDialog):
def __init__(self):
super().__init__()
self.tableWidget = QTableWidget()
self.result =
button = QPushButton("Create a dictionary from QtableWidgetItem")
button.clicked.connect(self.generateCsvData) # <---
self.layout = QVBoxLayout()
self.layout.addWidget(self.tableWidget)
self.layout.addWidget(button)
self.setLayout(self.layout)
self.tableWidget.setRowCount(4)
self.tableWidget.setColumnCount(5)
for i in range(4):
for j in range(5):
if j == 0:
item = QTableWidgetItem("111".format(i))
else:
item = QTableWidgetItem("Item -".format(i, j))
item.setTextAlignment(Qt.AlignHCenter)
self.tableWidget.setItem(i, j, item)
def generateCsvData(self): # <---
for row in range(self.tableWidget.rowCount()):
v = []
for column in range(self.tableWidget.columnCount()):
if column == 0:
k = self.tableWidget.item(row, column).text()
else:
item = self.tableWidget.item(row, column).text()
v.append(item)
self.result[k] = v
print("n key value")
[ print(k, v) for k, v in self.result.items()]
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Example()
w.show()
sys.exit(app.exec_())
Thanks Bro, but i didn't mention that i need the dict with this fomrat: result = '1111':['Capital 1','145321','94565','','','','74651','','','24651','','',''], '1112':['Capital 2','65115','','6149','6645','555641','','','','41245','98416','',''], '1113':['Capital 3','544453','','45345453','','555641','434556','','453453','','98416','','453453'], ........., the key is an int and the value is a list if you remember from the previous questions
– Anass Belmaati
Mar 23 at 19:31
1
@AnassBelmaati Attach an image of what yourtableWidget
looks like with data
– S. Nick
Mar 23 at 19:44
i attached it bro check it
– Anass Belmaati
Mar 23 at 20:08
@AnassBelmaati see update
– S. Nick
Mar 23 at 21:09
1
When i added this instruction: self.result[v[0]] = (v[1:]) it's creating for every row a Dict and every time it append an item, use it to figure out what i'm talking about, and thank you.
– Anass Belmaati
Mar 23 at 21:37
add a comment |
Try it:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Example(QDialog):
def __init__(self):
super().__init__()
self.tableWidget = QTableWidget()
self.result =
button = QPushButton("Create a dictionary from QtableWidgetItem")
button.clicked.connect(self.generateCsvData) # <---
self.layout = QVBoxLayout()
self.layout.addWidget(self.tableWidget)
self.layout.addWidget(button)
self.setLayout(self.layout)
self.tableWidget.setRowCount(4)
self.tableWidget.setColumnCount(2)
for i in range(4):
for j in range(2):
item = QTableWidgetItem("Item -".format(i, j))
item.setTextAlignment(Qt.AlignHCenter)
self.tableWidget.setItem(i, j, item)
def generateCsvData(self): # <---
for row in range(self.tableWidget.rowCount()):
for column in range(self.tableWidget.columnCount()):
item = self.tableWidget.item(row, column).text()
k = ":0>3::0>3".format(row, column)
v = "".format(item)
self.result[k] = v
print("n key value")
[ print(k, v) for k, v in self.result.items()]
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Example()
w.show()
sys.exit(app.exec_())
Update
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Example(QDialog):
def __init__(self):
super().__init__()
self.tableWidget = QTableWidget()
self.result =
button = QPushButton("Create a dictionary from QtableWidgetItem")
button.clicked.connect(self.generateCsvData) # <---
self.layout = QVBoxLayout()
self.layout.addWidget(self.tableWidget)
self.layout.addWidget(button)
self.setLayout(self.layout)
self.tableWidget.setRowCount(4)
self.tableWidget.setColumnCount(5)
for i in range(4):
for j in range(5):
if j == 0:
item = QTableWidgetItem("111".format(i))
else:
item = QTableWidgetItem("Item -".format(i, j))
item.setTextAlignment(Qt.AlignHCenter)
self.tableWidget.setItem(i, j, item)
def generateCsvData(self): # <---
for row in range(self.tableWidget.rowCount()):
v = []
for column in range(self.tableWidget.columnCount()):
if column == 0:
k = self.tableWidget.item(row, column).text()
else:
item = self.tableWidget.item(row, column).text()
v.append(item)
self.result[k] = v
print("n key value")
[ print(k, v) for k, v in self.result.items()]
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Example()
w.show()
sys.exit(app.exec_())
Thanks Bro, but i didn't mention that i need the dict with this fomrat: result = '1111':['Capital 1','145321','94565','','','','74651','','','24651','','',''], '1112':['Capital 2','65115','','6149','6645','555641','','','','41245','98416','',''], '1113':['Capital 3','544453','','45345453','','555641','434556','','453453','','98416','','453453'], ........., the key is an int and the value is a list if you remember from the previous questions
– Anass Belmaati
Mar 23 at 19:31
1
@AnassBelmaati Attach an image of what yourtableWidget
looks like with data
– S. Nick
Mar 23 at 19:44
i attached it bro check it
– Anass Belmaati
Mar 23 at 20:08
@AnassBelmaati see update
– S. Nick
Mar 23 at 21:09
1
When i added this instruction: self.result[v[0]] = (v[1:]) it's creating for every row a Dict and every time it append an item, use it to figure out what i'm talking about, and thank you.
– Anass Belmaati
Mar 23 at 21:37
add a comment |
Try it:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Example(QDialog):
def __init__(self):
super().__init__()
self.tableWidget = QTableWidget()
self.result =
button = QPushButton("Create a dictionary from QtableWidgetItem")
button.clicked.connect(self.generateCsvData) # <---
self.layout = QVBoxLayout()
self.layout.addWidget(self.tableWidget)
self.layout.addWidget(button)
self.setLayout(self.layout)
self.tableWidget.setRowCount(4)
self.tableWidget.setColumnCount(2)
for i in range(4):
for j in range(2):
item = QTableWidgetItem("Item -".format(i, j))
item.setTextAlignment(Qt.AlignHCenter)
self.tableWidget.setItem(i, j, item)
def generateCsvData(self): # <---
for row in range(self.tableWidget.rowCount()):
for column in range(self.tableWidget.columnCount()):
item = self.tableWidget.item(row, column).text()
k = ":0>3::0>3".format(row, column)
v = "".format(item)
self.result[k] = v
print("n key value")
[ print(k, v) for k, v in self.result.items()]
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Example()
w.show()
sys.exit(app.exec_())
Update
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Example(QDialog):
def __init__(self):
super().__init__()
self.tableWidget = QTableWidget()
self.result =
button = QPushButton("Create a dictionary from QtableWidgetItem")
button.clicked.connect(self.generateCsvData) # <---
self.layout = QVBoxLayout()
self.layout.addWidget(self.tableWidget)
self.layout.addWidget(button)
self.setLayout(self.layout)
self.tableWidget.setRowCount(4)
self.tableWidget.setColumnCount(5)
for i in range(4):
for j in range(5):
if j == 0:
item = QTableWidgetItem("111".format(i))
else:
item = QTableWidgetItem("Item -".format(i, j))
item.setTextAlignment(Qt.AlignHCenter)
self.tableWidget.setItem(i, j, item)
def generateCsvData(self): # <---
for row in range(self.tableWidget.rowCount()):
v = []
for column in range(self.tableWidget.columnCount()):
if column == 0:
k = self.tableWidget.item(row, column).text()
else:
item = self.tableWidget.item(row, column).text()
v.append(item)
self.result[k] = v
print("n key value")
[ print(k, v) for k, v in self.result.items()]
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Example()
w.show()
sys.exit(app.exec_())
Try it:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Example(QDialog):
def __init__(self):
super().__init__()
self.tableWidget = QTableWidget()
self.result =
button = QPushButton("Create a dictionary from QtableWidgetItem")
button.clicked.connect(self.generateCsvData) # <---
self.layout = QVBoxLayout()
self.layout.addWidget(self.tableWidget)
self.layout.addWidget(button)
self.setLayout(self.layout)
self.tableWidget.setRowCount(4)
self.tableWidget.setColumnCount(2)
for i in range(4):
for j in range(2):
item = QTableWidgetItem("Item -".format(i, j))
item.setTextAlignment(Qt.AlignHCenter)
self.tableWidget.setItem(i, j, item)
def generateCsvData(self): # <---
for row in range(self.tableWidget.rowCount()):
for column in range(self.tableWidget.columnCount()):
item = self.tableWidget.item(row, column).text()
k = ":0>3::0>3".format(row, column)
v = "".format(item)
self.result[k] = v
print("n key value")
[ print(k, v) for k, v in self.result.items()]
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Example()
w.show()
sys.exit(app.exec_())
Update
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Example(QDialog):
def __init__(self):
super().__init__()
self.tableWidget = QTableWidget()
self.result =
button = QPushButton("Create a dictionary from QtableWidgetItem")
button.clicked.connect(self.generateCsvData) # <---
self.layout = QVBoxLayout()
self.layout.addWidget(self.tableWidget)
self.layout.addWidget(button)
self.setLayout(self.layout)
self.tableWidget.setRowCount(4)
self.tableWidget.setColumnCount(5)
for i in range(4):
for j in range(5):
if j == 0:
item = QTableWidgetItem("111".format(i))
else:
item = QTableWidgetItem("Item -".format(i, j))
item.setTextAlignment(Qt.AlignHCenter)
self.tableWidget.setItem(i, j, item)
def generateCsvData(self): # <---
for row in range(self.tableWidget.rowCount()):
v = []
for column in range(self.tableWidget.columnCount()):
if column == 0:
k = self.tableWidget.item(row, column).text()
else:
item = self.tableWidget.item(row, column).text()
v.append(item)
self.result[k] = v
print("n key value")
[ print(k, v) for k, v in self.result.items()]
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Example()
w.show()
sys.exit(app.exec_())
edited Mar 23 at 21:08
answered Mar 23 at 19:05
S. NickS. Nick
4,371268
4,371268
Thanks Bro, but i didn't mention that i need the dict with this fomrat: result = '1111':['Capital 1','145321','94565','','','','74651','','','24651','','',''], '1112':['Capital 2','65115','','6149','6645','555641','','','','41245','98416','',''], '1113':['Capital 3','544453','','45345453','','555641','434556','','453453','','98416','','453453'], ........., the key is an int and the value is a list if you remember from the previous questions
– Anass Belmaati
Mar 23 at 19:31
1
@AnassBelmaati Attach an image of what yourtableWidget
looks like with data
– S. Nick
Mar 23 at 19:44
i attached it bro check it
– Anass Belmaati
Mar 23 at 20:08
@AnassBelmaati see update
– S. Nick
Mar 23 at 21:09
1
When i added this instruction: self.result[v[0]] = (v[1:]) it's creating for every row a Dict and every time it append an item, use it to figure out what i'm talking about, and thank you.
– Anass Belmaati
Mar 23 at 21:37
add a comment |
Thanks Bro, but i didn't mention that i need the dict with this fomrat: result = '1111':['Capital 1','145321','94565','','','','74651','','','24651','','',''], '1112':['Capital 2','65115','','6149','6645','555641','','','','41245','98416','',''], '1113':['Capital 3','544453','','45345453','','555641','434556','','453453','','98416','','453453'], ........., the key is an int and the value is a list if you remember from the previous questions
– Anass Belmaati
Mar 23 at 19:31
1
@AnassBelmaati Attach an image of what yourtableWidget
looks like with data
– S. Nick
Mar 23 at 19:44
i attached it bro check it
– Anass Belmaati
Mar 23 at 20:08
@AnassBelmaati see update
– S. Nick
Mar 23 at 21:09
1
When i added this instruction: self.result[v[0]] = (v[1:]) it's creating for every row a Dict and every time it append an item, use it to figure out what i'm talking about, and thank you.
– Anass Belmaati
Mar 23 at 21:37
Thanks Bro, but i didn't mention that i need the dict with this fomrat: result = '1111':['Capital 1','145321','94565','','','','74651','','','24651','','',''], '1112':['Capital 2','65115','','6149','6645','555641','','','','41245','98416','',''], '1113':['Capital 3','544453','','45345453','','555641','434556','','453453','','98416','','453453'], ........., the key is an int and the value is a list if you remember from the previous questions
– Anass Belmaati
Mar 23 at 19:31
Thanks Bro, but i didn't mention that i need the dict with this fomrat: result = '1111':['Capital 1','145321','94565','','','','74651','','','24651','','',''], '1112':['Capital 2','65115','','6149','6645','555641','','','','41245','98416','',''], '1113':['Capital 3','544453','','45345453','','555641','434556','','453453','','98416','','453453'], ........., the key is an int and the value is a list if you remember from the previous questions
– Anass Belmaati
Mar 23 at 19:31
1
1
@AnassBelmaati Attach an image of what your
tableWidget
looks like with data– S. Nick
Mar 23 at 19:44
@AnassBelmaati Attach an image of what your
tableWidget
looks like with data– S. Nick
Mar 23 at 19:44
i attached it bro check it
– Anass Belmaati
Mar 23 at 20:08
i attached it bro check it
– Anass Belmaati
Mar 23 at 20:08
@AnassBelmaati see update
– S. Nick
Mar 23 at 21:09
@AnassBelmaati see update
– S. Nick
Mar 23 at 21:09
1
1
When i added this instruction: self.result[v[0]] = (v[1:]) it's creating for every row a Dict and every time it append an item, use it to figure out what i'm talking about, and thank you.
– Anass Belmaati
Mar 23 at 21:37
When i added this instruction: self.result[v[0]] = (v[1:]) it's creating for every row a Dict and every time it append an item, use it to figure out what i'm talking about, and thank you.
– Anass Belmaati
Mar 23 at 21:37
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55316440%2fhow-to-create-a-dictionary-from-qtablewidgetitem%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown