gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:39:29 25 4
gpt4 key购买 nike

我正在尝试通过全身心投入并尝试完成工作来学习 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 尝试使用迭代器协议(protocol)使用 Post.__getitem__ 对其进行迭代,然后您会遇到 Key 0 异常

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com