I have a row named filename
in postgresql table named xml_joblist
which contain many files, and a list named files_name
in python which contain several files that are sorted after some process. I want to compare filename
& files_name
and check whether there are any files matching.
|filename |
|---------|
|file_111 |
|file_555 |
|file_888 |
|file_333 |
|file_445 |
| . |
| . |
| goes-on |
the above given is the filename
row in postgresql table
files_name = [file_789, file_456, file_555, file_111]
the above given is the files_name list i python
How can i write a sql statement to do this process in python?
Expected result:
matchin_files = [file_555, file_111]
5
Answers
If you’re using psycopg2 directly, you can use its tuple to
SELECT IN
capabilities. You then retrieve the file name directly with a list comprehension.See the following demo a table that contains
file_100
through tofile_109
.If you use anything else (like SQLAlchemy), please leave a comment.
Set up table:
Python code:
This uses
psycopg2
list adaptation:to select those file names that are in the
file_names
list that are also in thexml_joblist
table using the ANY operator:Connect to the postgres db
Get the
xml_joblist
tableSelect
filename
fromxml_joblist
table and compare it tofiles_name
This gives
matchin_files
as a list like this-If you are using a library such as psycopg2, then the cur.execute method() will return you a list of tuples, with each tuple containing a single item.
So essentially your question simplifies to
How to compare a list of tuples against a list.
One of the ways to do so is to use something like below
Other way is to use set.
you can use SQLAlchemy IN comparison operator(check here for more inforamtion!)