Reputation: 4740
I'm trying to loop through a dictionary and append to a string- here is the code:
mylist= {'name':'james', 'age': '23', 'time': 'next'}
myquery = "select * from players where"
for k, v in mylist.items():
myquery += "%s=%s and" % (k, v),
print myquery
This is prints 'select * from maintable where age=23 and name=jame and time=next and'
My problem is that there is an 'and' at the end of that result.
How do I run that for loop without having that last and?
Any help would be appreciated.
Upvotes: 1
Views: 272
Reputation: 11155
At the end of the for loop add this statement, which removes the and from the query statement.
if myquery.endswith('and'):
myquery = myquery[:-3]
Upvotes: 2
Reputation: 1124508
Use the str.join()
method to join strings together with an ' and '
delimiter:
myquery = "select * from players where {}".format(
' and '.join('{}={}'.format(k, v) for k, v in mylist.iteritems()))
Demo:
>>> mylist= {'name':'james', 'age': '23', 'time': 'next'}
>>> "select * from players where {}".format(
... ' and '.join('{}={}'.format(k, v) for k, v in mylist.iteritems()))
'select * from players where age=23 and name=james and time=next'
However, it looks as if you are building a SQL query; don't interpolate the values in that case, use SQL parameters instead:
myquery = "select * from players where {}".format(
' and '.join('{}=?'.format(k) for k in mylist))
and then use cursor.execute(myquery, mylist.values())
to pass the parameters to the database adapter.
Check what format your database adapter uses; some use %s
(C sprintf style) and others use ?
as placeholders.
Upvotes: 5