首页 > 解决方案 > 如何检查文件中是否存在特定字典

问题描述

我需要知道我打开的 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'

标签: pythondictionary

解决方案


您可以检查字典中的键:

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 


推荐阅读