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

bla*_*ite 2 python dictionary for-loop beautifulsoup python-2.7

我将总统演讲的日期和每个演讲的日期存储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>,...]
Run Code Online (Sandbox Code Playgroud)

而且end_link样子:

['/president/obama/speeches/speech-4427', '/president/obama/speeches/speech-4424',...]
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

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)]
Run Code Online (Sandbox Code Playgroud)

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

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

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

Cal*_*uer 5

您没有将该键的值设置为任何值,因此Python认为您正在尝试读取该键.date_dict字典为空.

你需要设置一个值,所以像这样:

date_dict[date] = filename
Run Code Online (Sandbox Code Playgroud)

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

date_dict['key'] = value
Run Code Online (Sandbox Code Playgroud)

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

关于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]) 
Run Code Online (Sandbox Code Playgroud)

  • 请注意,在一般情况下,转换为字符串会冒使用`tuple`键可以避免的错误.`date_dict [filename,date] = end_link`避免了字符串格式化开销,同样合法,并且将键的组件分开,这样您可以在迭代时单独使用每个组件,而不是尝试解析字符串.如果需要将密钥用于输出,可以随后格式化密钥. (2认同)