简体   繁体   中英

method returns a dict, checking for existence of key returns KeyError: 0

I'm trying to learn Python by throwing myself in and trying to get stuff done. I've hit a snag on something basic. Can I have some help?

I'm using os.walk to find my (Jekyll) markdown files, load their frontmatter via python-frontmatter , and gather a list of feature_image properties that may or may not be in each file.

According to the library's docs, the frontmatter is accessible as a dictionary, and my Googling says I should be able to use a

if "property" in dict:

construct to see if property key is defined in the dict, but when I try I'm getting a "KeyError: 0" error.

This is how far I've gotten:

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"])

Here's what I'm getting back when I run this script

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

Thanks for your help!

Short answer use:

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

Longer answer:

The Post class does not provide a __contain__ method so python tries to iterate it using the iterator protocol using Post.__getitem__ and then you blow up with the Key 0 Exception

For more info, try looking up how python iterate over things :)

If you are not sure what the value is in the dictionary, then the best option would be to use dict.get("key", "default value") , if value do not in dictionary by default this method will return None . In boolean context None == False .

In your case it will be looking as:

if post.get("feature_image"):
    # do smth

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM