简体   繁体   中英

Nested dictionary to single dictionary

So, i'm building a little tool to save errors and their solutions as a knowledge base. It is stored in a SQL Database (i'm using pyodbc). The users don't have access to the database, just the GUI. The GUI has three buttons, one for add a new ErrorID, one for search for an ErrorID (if it exists in the database), and one for delete. It has too a text panel where it should show the solution of the error searched.

So, need to extract the columns and rows of my DB and put them in a dictionary, then I need to run through that dict in search for the error searched and show it solution on the text panel. My issue is that the dict that I get has this form: {{('Error', 1): ('Solution', one)}} and so on, so I cannot seem to run succesfully through it and show ONLY the word "one" on the text panel. In other words, when I search "1", it should print "one" on the text panel.

My question is: How can I transform this {{('Error', 1): ('Solution', one)}} INTO this {"1": "one"} ?

Edit: Sorry, I forgot to add some parts of my code.

This part is what appends every row in a dict:

readsql = sql_conn.sql()
readsql.sqlread()
columns = [column[0] for column in readsql.cursorv.description]
results = []
for row in readsql.cursorv.fetchall():
    results.append(zip(columns, row))
results = dict(results)

I tried to do this, like storing part of the dict that I know it's gonna show on a string named, well, string. And then compare it to 'k' in the for loop, but it doesn't work.

string = "('Error', " + str(error_number) + ")"
for k in results.keys():
    if k == string:
        post = readsql.cursorv.execute('SELECT * FROM master.dbo.Errors WHERE Error = (?)', (error_number))
        text_area.WriteText(post)
        break

Here is sql class:

class sql():

    def __init__(self):
        self.conn = pyodbc.connect('Driver={SQL Server};'
                            'Server=.\SQLEXPRESS;'
                            'Database=master;'
                            'Trusted_Connection=yes;')
        # cursor variable
        self.cursorv = self.conn.cursor()

    def sqlread(self):
        self.cursorv.execute('SELECT * FROM master.dbo.Errors')

Your problem comes from the following code unnecessarily zipping the column headers into the resulting dict:

for row in readsql.cursorv.fetchall():
    results.append(zip(columns, row))
results = dict(results)

You can instead construct the desired dict directly from the sequence of tuples returned by the fetchall method:

results = dict(readsql.cursorv.fetchall())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM