python - 方法返回一个字典,检查键是否存在返回 KeyError : 0

标签 python python-3.x dictionary

我正在尝试通过全身心投入并努力完成工作来学习Python。我在一些基本的事情上遇到了障碍。我可以帮忙吗?

我正在使用 os.walk 来查找我的 (Jekyll) markdown 文件,通过 python-frontmatter 加载它们的 frontmatter ,并收集每个文件中可能存在或不存在的 feature_image 属性列表。

根据图书馆的文档,frontmatter 可以作为字典访问,我的谷歌搜索说我应该能够使用

if "property" in dict:

构造以查看字典中是否定义了属性键,但是当我尝试时,我收到“KeyError:0”错误。

这就是我已经走了多远:

import os
import frontmatter

markdownExt = ("md", "markdown")
templateDir = "jekyll/_posts"

for root, dirs, files in os.walk(templateDir, topdown=False):
    for name in files:
        if name.endswith(markdownExt):
            post = frontmatter.load( os.path.join(root, name) )
            if "feature_image" in post:
                print(post["feature_image"])

这是我运行此脚本时得到的结果

Traceback (most recent call last):
  File "./test.py", line 14, in <module>
    if "feature_image" in post:
  File "/usr/local/lib/python3.5/site-packages/frontmatter/__init__.py", line 124, in __getitem__
    return self.metadata[name]
KeyError: 0

感谢您的帮助!

最佳答案

简答题使用:

if "feature_image" in post.keys(): #see the keys function?

更长的答案:

Post 类不提供 __contain__ 方法,因此 python 尝试使用 Post.__getitem__ 使用迭代器协议(protocol)来迭代它,然后您会因 Key 0 异常而崩溃

有关更多信息,请尝试查找 python 如何迭代事物:)

关于python - 方法返回一个字典,检查键是否存在返回 KeyError : 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34710633/

相关文章:

java - 具有方便符号的键值集合

r - 在 R 中使用 expand.grid 应用函数

python - 使用 range() 修改 x 和 y 以使用 Pythonturtle 创建网格

python - CalledProcessError 退出状态代码 5

python-3.x - 如何在aws Glue中将json写回s3?

python - 无法在打开端口转发的另一台 PC 上访问 MySQL 数据库

python - 构建连接日志系统

python - 在 python shell 中运行 telnet 时的错误消息

python - 如何判断 __iter__ 是由 dict 还是 list 调用?

python - 如何从列表中定位 python 小部件标签?