python - List Comprehension returns empty list -
i'm trying query mongodb database , throw 2 sets of results ('_id' , 'team') 2 separate lists.
import pymongo client = pymongo.mongoclient('localhost:27017') db = client['db_name'] query = {'team': {'$exists': 1}} projection = {'_id': 1, 'team': 1} data = db['collection_name'].find(query, projection) # line 9 id_list = [value dict in data key, value in dict.iteritems() if key == '_id'] teams_list = [value dict in data key, value in dict.iteritems() if key == 'team'] print id_list print teams_list client.close()
for code above, 'id_list' expected 'teams_list' empty. when put 'teams_list' before 'id_list' expected 'teams_list' output , 'id_list' empty. , when repeat data call (line 9) in between 2 list comprehensions expected output both lists.
any idea why happening?
you need define data
as:
data = list(db['collection_name'].find(query, projection))
as find()
returns generator. once iterate values, lost. need store them list
. here list()
i.e. stores items returns generator list.
instead of iterating list twice, better way 2 single loop as:
id_list, teams_list = [], [] # v `dict` in-built data type, should not using variable d in data: key, value in d.iteritems(): if key == '_id': id_list.append(value) elif key == 'team': teams_list.append(value)
refer generator wiki more information related generators
Comments
Post a Comment