python - 如何检查文件中是否存在特定字典
问题描述
我需要知道我打开的 json 文件中是否存在一个名为“行为”的字典和一个名为 apistats 的键,如果它存在,我可以进行进一步处理,如果它不存在,则打开下一个文件
我尝试过设置带有 apistats 的字典是否存在的条件,但它给出了错误。此外,我不能只检查行为中的关键 apistats,因为对于某些文件,行为字典根本不存在
for filename in glob.glob('*.json'):
with open(filename) as json_file:
data=json.load(json_file)
if data['behavior']['apistats']:
print ('exists')
else:
print("doesn't")
Expected:
exists
exists
doesn't
Actual Output:
File "C:/Users/sidra/Desktop/extractor/ectractor.py", line 12, in <module>
if data['behavior']['apistats']:
KeyError: 'apistats'
解决方案
您可以检查字典中的键:
if key in dictionary:
...
例如:
if "behavior" in data:
if "apistats" in data["behavior"]:
...
或者只是将您的控件放在尝试中 - 除了块:
try:
if some control that throws exception:
...
except:
print("does not exist")
pass
推荐阅读
- angular - 在 Angular 8 应用程序中实现会话存储
- kendo-ui - 如何更改剑道网格的背景颜色
- python - Python拆分一个字符串然后正则表达式
- python - 来自 tkinter 和页面上的按钮的新窗口
- android - 安装不再在 Android Q 中工作的自签名证书
- sql - 将数据库中的多列合并为一列?
- node.js - 我想创建一个角度应用程序来显示像 Jsbin 这样的实时代码预览
- c# - 带有 HScrollBar 控件的滚动面板
- r - 将具有三个输入的自己的函数应用于数据框
- networking - 如何使 TAP 适配器接受来自 PC 的所有流量?