在迭代多个for循环时创建字典?

时间:2015-10-13 20:56:11

标签: python python-2.7 for-loop dictionary beautifulsoup

我将总统演讲的日期和每个演讲的filename存储在字典中。 speeches对象如下所示:

[<a href="/president/obama/speeches/speech-4427">Acceptance Speech at the Democratic National Convention (August 28, 2008)</a>,
<a href="/president/obama/speeches/speech-4424">Remarks on Election Night (November 4, 2008)</a>,...]

end_link看起来像:

['/president/obama/speeches/speech-4427', '/president/obama/speeches/speech-4424',...]

这是我的代码:

date_dict = {}
for speech in speeches:
    text = speech.get_text(strip=True)
    date = text[text.index("(") + 1:text.rindex(")")]
    end_link = [tag.get('href') for tag in speeches if tag.get('href') is not None]
    for x in end_link:
        splitlink = x.split("/")
        president = splitlink[2]
        speech_num = splitlink[4]
        filename = "{0}_{1}".format(president,speech_num)
        if 2 == 2:
            f = date_dict['{0} {1}'.format(filename,date)]

我得到了正确的日期输出(例如August 15, 1999),filename没问题。现在,我只是想加入这两个,并收到以下错误:

date_dict['{0} {1}'.format(filename,date)]
KeyError: 'obama_speech-4427 August 28, 2008'

我真的不知道从哪里开始。

1 个答案:

答案 0 :(得分:5)

您没有将该密钥的值设置为任何内容,因此Python认为您正在尝试读取该密钥。 date_dict字典为空。

您需要设置一个值,如下所示:

date_dict[date] = filename

字典有键和值。要分配到字典,您可以执行以下操作:

date_dict['key'] = value

加入部分没有问题。 '{0} {1}'.format(filename,date)很好,但您可能需要下划线而不是空格。或者如果要在网站上发布,可能会破折号。

Related question about KeyError

修改

根据我们的讨论,我认为您需要这样做:

date_dict = {}
for speech in speeches:
    text = speech.get_text(strip=True)
    date = text[text.index("(") + 1:text.rindex(")")]
    end_link = [tag.get('href') for tag in speeches if tag.get('href') is not None]
    for x in end_link:
        splitlink = x.split("/")
        president = splitlink[2]
        speech_num = splitlink[4]
        filename = "{0}_{1}".format(president,speech_num)
        if 2 == 2:
            date_dict[filename] = date

# Prints name date for a given file(just an example)
print("File", filname, "recorded on", date_dict[filename])