python mysql dictionary
I have been using the dictcursor in MySQL with Python, the problem is how I can retrieve an specific record without having to iterate in all the dictionary, actually I am using this:
data=cursor.fechall
for item in data:
if item["article"]==articledesc:
do something
break
is there a way to access the element of the dictionary created directly, without having to iterate over all the elements with a for开发者_运维百科 loop
thanks
If you only require a single article, then change your query to add a where clause:
SELECT ...
FROM ...
WHERE article = %s
Filtering a result set having retrieved more than you need is not a good idea from an efficiency point of view.
If you're retrieving a larger resultset and picking multiple articles out by name later on, you could build a rudimentary index in your first pass; then use this to efficiently access the rows by name:
data = cursor.fetchall()
article_index = dict((item["article"], item) for item in data)
article = article_index.get(articledesc)
if article:
#do something
Not directly, you can build another dictionary, but it is an implicit loop:
data_article = dict((item['article'], item) for item in data)
and then you can access data directly:
myitem = dict_article[articledesc]
精彩评论