开发者

Cannot add new items into python dictionary

开发者 https://www.devze.com 2023-01-27 09:28 出处:网络
Hi I\'m n开发者_开发技巧ew to python. I am trying to add different key value pairs to a dictionary depending on different if statements like the following:

Hi I'm n开发者_开发技巧ew to python. I am trying to add different key value pairs to a dictionary depending on different if statements like the following:

def getContent(file)
    for line in file:

        content = {}

        if line.startswith(titlestart):
            line = line.replace(titlestart, "")
            line = line.replace("]]></title>", "")
            content["title"] = line

        elif line.startswith(linkstart):
            line = line.replace(linkstart, "")
            line = line.replace("]]>", "")
            content["link"] = line

        elif line.startswith(pubstart):
            line = line.replace(pubstart, "")
            line = line.replace("</pubdate>", "")
            content["pubdate"] = line

    return content

print getContent(list)

However, this always returns the empty dictionary {}.

I thought it was variable scope issue at first but that doesn't seem to be it. I feel like this is a very simple question but I'm not sure what to google to find the answer.

Any help would be appreciated.


You reinitialize content for every line, move the initialization outside of the loop:

def getContent(file)

    content = {}

    for line in file:

etc.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号