如何解决如何访问和过滤具有多个值的字典?
我正在使用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','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','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)
解决方法
欢迎使用stackoverflow。您可以使用dict理解来过滤文档。在下面的示例中,Exception in Tkinter callback
Traceback (most recent call last):
File "textract\parsers\__init__.py",line 69,in process
File "importlib\__init__.py",line 127,in import_module
File "<frozen importlib._bootstrap>",line 1006,in _gcd_import
File "<frozen importlib._bootstrap>",line 983,in _find_and_load
File "<frozen importlib._bootstrap>",line 965,in _find_and_load_unlocked
ModuleNotFoundError: No module named 'textract.parsers.pdf_parser'
During handling of the above exception,another exception occurred:
Traceback (most recent call last):
File "tkinter\__init__.py",line 1705,in __call__
File "PDF_Splitter.py",line 383,in UploadAction2
File "PDF_Splitter.py",line 120,in splitPDF
File "textract\parsers\__init__.py",line 72,in process
File "textract\exceptions.py",line 21,in __init__
File "textract\parsers\__init__.py",line 89,in _get_available_extensions
File "c:\users\V\appdata\local\programs\python\python37-32\lib\re.py",line 234,in compile
return _compile(pattern,flags)
File "c:\users\V\appdata\local\programs\python\python37-32\lib\re.py",line 286,in _compile
p = sre_compile.compile(pattern,flags)
File "c:\users\V\appdata\local\programs\python\python37-32\lib\sre_compile.py",line 764,in compile
p = sre_parse.parse(p,flags)
File "c:\users\V\appdata\local\programs\python\python37-32\lib\sre_parse.py",line 930,in parse
p = _parse_sub(source,pattern,flags & SRE_FLAG_VERBOSE,0)
File "c:\users\V\appdata\local\programs\python\python37-32\lib\sre_parse.py",line 426,in _parse_sub
not nested and not items))
File "c:\users\V\appdata\local\programs\python\python37-32\lib\sre_parse.py",line 507,in _parse
code = _escape(source,this,state)
File "c:\users\V\appdata\local\programs\python\python37-32\lib\sre_parse.py",line 369,in _escape
raise source.error("incomplete escape %s" % escape,len(escape))
re.error: incomplete escape \U at position 2
检查该项目是嵌入式文档,而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','tv-38': {'titel': 'TV program','price': 5,'tooltip': 'long','explenation': 'longer','tv-70': {'titel': 'TV program','tooltip': 'boring','explenation': 'very boring','standard': True}}
filtered_doc = {k: v for k,dict) and v.get('standard') is True}
pprint.pprint(filtered_doc)
,
您可以只使用列表推导(如果您不想在MongoDB本身中对其进行过滤):
filtered_items = [x for x in mydoc.items() if x[1]['standard']]
这将创建一个项目列表,其中第二个元素(返回的字典)的值为True(如果可能不会出现键“标准”,只需使用x[1].get('standard',False)
即可)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。