首页 > 解决方案 > 如何访问和过滤具有多个值的字典?

问题描述

我正在使用 pymongo 访问我的 MongoDB 中的文档。现在我想根据值标准是否为真过滤返回的目录。

目前我的代码如下所示:

db = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = db.myclient["pricing"]
mycol = mydb["locations"]

mydoc = db["pricing"]["prices"].find_one({"location":"test"})

for i in mydoc.items():
    print(i)

此代码返回以下内容:

('_id', ObjectId('5f43c555dec06035ccfd2eac'))
('location', 'test')
('rent-40', {'titel': 'Base rent', 'price': 620, 'tooltip': 'test i think ', 'explenation': 'longer explanation', 'standard': False})
('rent-32', {'titel': 'Base rent', 'price': 600, 'tooltip': 'nana', 'explenation': 'very long explenation', 'standard': True})
('water', {'titel': 'Water cost', 'price': 10, 'tooltip': 'test', 'explenation': 'long explenation', 'standard': True})
  ('tv-38', {'titel': 'TV program', 'price': 5, 'tooltip': 'long', 'explenation': 'longer', 'standard': False})
('tv-70', {'titel': 'TV program', 'price': 5, 'tooltip': 'boring', 'explenation': 'very boring', 'standard': True})

最终结果应该是standard == True. 我非常感谢您在这方面的帮助,因为我正在努力解决数据嵌套的问题。

也许不是最优雅的解决方案,但它对我有用。问题是前两个项目的格式不同,所以我把它们剪掉了,然后它就很简单了:

standard = []
c =list(mydoc.items())
#print(c[2:])
for i in c[2:]:
    if i[1]["standard"] == True:
        standard.append(i)
else:
    print("hi")
print(standard)

标签: pythondictionaryfilterpymongo

解决方案


欢迎来到stackoverflow。您可以使用 dict 理解来过滤文档。在下面的示例中,isinstance(v, dict)检查该项目是否为嵌入式文档并且v.get('standard') is True是您的过滤器。

filtered_doc = {k: v for k, v in mydoc.items() if isinstance(v, dict) and v.get('standard') is True}

工作示例:

import pprint

mydoc = {
    'location': 'test',
    'rent-40': {'titel': 'Base rent', 'price': 620, 'tooltip': 'test i think ', 'explenation': 'longer explanation', 'standard': False},
    'rent-32': {'titel': 'Base rent', 'price': 600, 'tooltip': 'nana', 'explenation': 'very long explenation', 'standard': True},
    'water': {'titel': 'Water cost', 'price': 10, 'tooltip': 'test', 'explenation': 'long explenation', 'standard': True},
    'tv-38': {'titel': 'TV program', 'price': 5, 'tooltip': 'long', 'explenation': 'longer', 'standard': False},
    'tv-70': {'titel': 'TV program', 'price': 5, 'tooltip': 'boring', 'explenation': 'very boring', 'standard': True}}

filtered_doc = {k: v for k, v in mydoc.items() if isinstance(v, dict) and v.get('standard') is True}
pprint.pprint(filtered_doc)

会给:

{'rent-32': {'explenation': 'very long explenation',
             'price': 600,
             'standard': True,
             'titel': 'Base rent',
             'tooltip': 'nana'},
 'tv-70': {'explenation': 'very boring',
           'price': 5,
           'standard': True,
           'titel': 'TV program',
           'tooltip': 'boring'},
 'water': {'explenation': 'long explenation',
           'price': 10,
           'standard': True,
           'titel': 'Water cost',
           'tooltip': 'test'}}

推荐阅读