使用Python和MongoDB从dict获取密钥

时间:2017-08-06 18:11:45

标签: python mongodb python-3.x dictionary pymongo

我正在尝试遍历数据集并检查我的MongoDB中是否存在数据。

我正在使用:

# Insert all venues
for venue in tree.find('Venues').findall('Venue'):

  #
  venue_id = venue.find('VenueID').text

  # Find venue
  existing_venue = db.venues.find_one({"venue_id": venue_id})

  # If exists
  if existing_venue:

    # Update existing
    print(existing_venue._id)

但是我在print(existing_venue._id)AttributeError: 'dict' object has no attribute '_id'的行中收到了错误。

如果我只是打印existing_venue(而不是existing_venue._id),我会看到词典包括键_id,所以我不明白为什么会这样。

如果我检查我知道已插入的任何其他密钥,则会发生完全相同的问题。

打印existing_venue时,我

{'_id': ObjectId('59875acef5ec4eb0c85c1aa0'), 'name': 'Empire State Building'}

1 个答案:

答案 0 :(得分:0)

我相信在python(3)中访问字典中键值对的正确方法是:dic [' key']。也许你可以试试这个(existing_venue [' _id']。

有关python中字典的更多信息,请参阅: https://docs.python.org/3/tutorial/datastructures.html(5.5)