访问python字典内的集合字段

2024-10-01 07:26:34 发布

您现在位置:Python中文网/ 问答频道 /正文

totalHotelsInTown=hotels.aggregate([ {"$group": {"_id": "$Town", "TotalRestaurantInTown": {"$sum":1}} } ])

NumOfHotelsInTown={}

for item in totalHotelsInTown:
    NumOfHotelsInTown[item['_id']]=item['TotalRestaurantInTown']

results = hotels.aggregate(
        [{"$match": {"cuisine": cuisine}},
         {"$group": {"_id": "$town", "HotelsCount": {"$sum": 1} }}, {"$project": {"HotelsCount":1,"Percent": {"$multiply": [{"$divide": ["$HotelsCount", NumOfHotelsInTown["$_id"]]}, 100]}}},  {"$sort": {"Percent": 1}},
{"$limit": 1}])

我想将"_id"字段的值作为键传递给python字典,但是解释器将"$_id"本身作为键而不是它的值,并因此给出一个KeyError。任何帮助都将不胜感激。谢谢

“NumOfHotelsInTown”字典包含地点和酒店数量的键值对

当我试图从NumOfHotelsInTown字典中检索值时, 我使用“$\u id”动态地给出密钥

我得到的确切错误是:

 {"$group": {"_id": "$borough", "HotelsCount": {"$sum": 1} }}, {"$project": {"HotelsCount":1,"Percent": {"$multiply": [{"$divide": ["$HotelsCount", NumOfHotlesInTown["$_id"]]}, 100]}}},  {"$sort": {"Percent": 1}},
KeyError: '$_id'

Tags: projectid字典groupitemmultiplyaggregatesum
1条回答
网友
1楼 · 发布于 2024-10-01 07:26:34

我知道您正在尝试做什么,但是您不能在MongbDBaggregate期间动态运行python代码

你应该做的是:

  1. 获取每个行政区的总计数(您已经完成)
  2. 获取某一特定美食(您拥有该美食的一部分)的每个行政区的总数
  3. 使用python比较这两个总数以生成百分比列表,而不是MongoDB

例如:

group_by_borough = {"$group": {"_id": "$borough", "TotalRestaurantInBorough": {"$sum":1}} }
count_of_restaurants_by_borough = my_collection.aggregate([group_by_borough])
restaurant_count_by_borough = {doc["_id"]: doc["TotalRestaurantInBorough"] for doc in count_of_restaurants_by_borough}

count_of_cuisines_by_borough = my_collection.aggregate([{"$match": {"cuisine": cuisine}}, group_by_borough])
cuisine_count_by_borough = {doc["_id"]: doc["TotalRestaurantInBorough"] for doc in count_of_cuisines_by_borough}

percentages = {}

for borough, count in restaurant_count_by_borough.items():
    percentages[borough] = cuisine_count_by_borough.get(borough, 0) / float(count) * 100

# And if you wanted it sorted you can use an OrderedDict

from collections import OrderedDict
percentages = OrderedDict(sorted(percentages.items(), key=lambda x: x[1]))

相关问题 更多 >