PanDe
PanDe

Reputation: 974

Combine two list into a Dict, Tuple

I am creating a rest-api using the Python+Flask_Restful combo, find it amazing. Currently, i am allowing user to run a sql-query using the browser and it works fine, but the problem is, headers information is not displayed in the response. Here is the code that i am using:

class RunCustomeSQL(Resource):
 def get(self, enter_db_name, query):
    if not os.path.isfile(enter_db_name+'.db'):
            raise BadRequest("Database Doesn't Exist. Please select a valid database")
    conn = sqlite3.connect(enter_db_name+'.db') 
    search_out = []
    cursor = conn.execute(query)
    row = None
    for row in cursor: 
            search_out.append(row)
    if not row:  #This means empty response
        raise BadRequest("No Results Found")
    conn.commit()       
    conn.close()
    return search_out

While, this code works great, it doesn't print the header values in the json-response. The current response is :

[
    [
        "dusiri_bibi", 
        "11", 
        "----------", 
        "     srt/None      ", 
        "14.30 MB", 
        "2017-12-13 23:43:54", 
        "C:/Test_Software/vc_redist.x64.exe"
    ],  
]

Expected Output :

[
    [
        "Machine Name" : "dusiri_bibi", 
        "LABEL"        : "11", 
        "PERMISSIONS"  : "----------", 
        "USER"         : "     srt/None      ", 
        "SIZE"         : "14.30 MB", 
        "CREATED"      : "2017-12-13 23:43:54", 
        "FILENAME"     : "C:/Test_Software/vc_redist.x64.exe"
    ],  
]

All the above text such as "machine name, label etc." are my table headers, I am not sure how to print them along with my output.

What if the user runs select user, size from table_name only

or

What if the user runs select * from table_name

In both scenario's, the output should display the table headers Thanks

UPDATE #1 (25 April) : I managed to answer my first question and able to display a proper json response if the user selects the SELECT * statement in SQL but still facing issue with the second piece of it

Here is the answer to first part if anyone is looking for it : Using Regex

row = None
if re.search(r'(?<=SELECT)(.*)(?=FROM)',query, re.IGNORECASE).group(1) == ' * ':
    for row in cursor: 
       search_out.append({'NAME' : row[0], 'LABEL_NUMBER' : row[1], 'PERM' : row[2], 'USER' : row[3] , 'SIZE' : row[4], 'DATE' : row[5], 'FILENAME' : row[6]})
    if not row:  #This means empty response
       raise BadRequest("No Results Found")

Part II : Unanswered Query:

For the second piece, i now have two list :

list_1 :  [[u'LABEL_NUMBER', u'PERM', u'FILENAME']]
list_2 :  [(u'11', u'----------', u'C:/Test_Software/26.avi'), (u'11', u'----------', u'C:/Test_Software/6.avi'), (u'11', u'-rwx------', u'C:/Test_Software/Debug/Current_Frame1.avi'), (u'10', u'-rwxrwx---', u'C:/Windows/WinSxS/boxed-split.avi')]

As you can see, i have two list and i want to combine them into a dict to show the response like this:

[
   {  
      LABEL_NUMBER : '11' ,
      PERM         : '-----------',
      FILENAME     : 'C:/Test_Software/26.avi'
   },
...
....
......
   {  
      LABEL_NUMBER : '10' ,
      PERM         : '-rwxrwx---',
      FILENAME     : 'C:/Windows/WinSxS/boxed-split.avi'
   },
]

i am using the following code to do the same :

chunks = [list_2[idx:idx+3] for idx in range(0, len(list_2), 3)]

output = []

for each in chunks:
    output.append(dict(zip(list_1, each)))

print(output)  

But, this is failing with "TypeError: unhashable type: 'list'", i understand that lists are mutable and which is why i am getting this error but then how can i get the desired dict response? what am i doing wrong here?

Upvotes: 2

Views: 62

Answers (1)

jpp
jpp

Reputation: 164773

You can use a list comprehension combined with zip for this:

list_1 =  [[u'LABEL_NUMBER', u'PERM', u'FILENAME']]
list_2 =  [(u'11', u'----------', u'C:/Test_Software/26.avi'), (u'11', u'----------', u'C:/Test_Software/6.avi'), (u'11', u'-rwx------', u'C:/Test_Software/Debug/Current_Frame1.avi'), (u'10', u'-rwxrwx---', u'C:/Windows/WinSxS/boxed-split.avi')]

d = [dict(zip(list_1[0], i)) for i in list_2]

Result:

[{'FILENAME': 'C:/Test_Software/26.avi',
  'LABEL_NUMBER': '11',
  'PERM': '----------'},
 {'FILENAME': 'C:/Test_Software/6.avi',
  'LABEL_NUMBER': '11',
  'PERM': '----------'},
 {'FILENAME': 'C:/Test_Software/Debug/Current_Frame1.avi',
  'LABEL_NUMBER': '11',
  'PERM': '-rwx------'},
 {'FILENAME': 'C:/Windows/WinSxS/boxed-split.avi',
  'LABEL_NUMBER': '10',
  'PERM': '-rwxrwx---'}]

Upvotes: 1

Related Questions