简体   繁体   中英

Looping Through Python Dictionary

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.

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.

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]

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