在Python中收集到2d列表

时间:2017-11-17 03:09:59

标签: python mongodb flask pymongo

我正在尝试将MongoDB集合传递给python 2d列表。我需要每个子列表只包含文档中每个键的值。例如,如果MongoDB文档是:

{
   _id: ObjectId("5099803df3f4948bd2f98392"),
   name: 'marie',
   age: '23',
   gender: 'female'
}

{
   _id: ObjectId("5099803df3f4948bd2f98391"),
   name: 'john',
   age: '43',
   gender: 'male'
}

我需要得到类似的东西:

[
  [ObjectId("5099803df3f4948bd2f98392"), 'marie', '23', 'female],
  [ObjectId("5099803df3f4948bd2f98391"), 'john', '43', 'male']
]

我是MongoDB和PyMongo的新手。现在,我能做的最接近的是:

people = mongo.db.population
people_key_list = ['_id', 'name', 'age', 'gender'] 
people_list = []

for item in people.find():
    people_list.append(item)

但结果的结构并不是我真正需要的:

[
  ['ObjectId("5099803df3f4948bd2f98392")','ObjectId("5099803df3f4948bd2f98391")'],
  ['marie','john'],['23','43'],['female','male']
]

我可以旋转2d列表,但我确信应该有一种方法可以从一开始就有效地生成我需要的结构......但是无法弄清楚如何。

1 个答案:

答案 0 :(得分:1)

您已经使用键的名称定义了Executing testMethod1() Running special setup for testMethod1() Executing testMethod2() =============================================== Default Suite Total tests run: 2, Failures: 0, Skips: 0 =============================================== ,因此只需对该列表执行map并提取值:

people_key_list

或者甚至只是嵌套map

from pymongo import MongoClient
from bson import ObjectId

data = [
  {
    '_id': ObjectId("5099803df3f4948bd2f98392"),
    'name': 'marie',
    'age': '23',
    'gender': 'female'
  },
  {
    '_id': ObjectId("5099803df3f4948bd2f98391"),
    'name': 'john',
    'age': '43',
    'gender': 'male'
  }
]

client = MongoClient();
db = client['test']

db.population.remove({})
db.population.insert_many(data)


people_key_list = ['_id', 'name', 'age', 'gender']
people_list = []

for person in db.population.find():
  people_list.append(map(lambda k: person[k],people_key_list))

print(people_list)

要么返回:

people_list = map(lambda person:
  map(lambda k: person[k],people_key_list),
  db.population.find()
)