开发者

Cannot add new items into python dictionary

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜