swaysteady
swaysteady

Reputation: 110

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!

Upvotes: 2

Views: 334

Answers (2)

Dmitry
Dmitry

Reputation: 41

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

Upvotes: 1

Yoav Glazner
Yoav Glazner

Reputation: 8066

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 :)

Upvotes: 3

Related Questions