Creating a dictionary while iterating through multiple for loops?

别说谁变了你拦得住时间么 提交于 2021-02-10 12:20:08

问题


I am storing the dates of Presidential speeches and each speech's respective filename in a dictionary. The speeches object looks like this:

[<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>,...]

And end_link looks like:

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

Here's my code:

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

I get the proper date output (e.g. August 15, 1999) and filename is fine. Now, I'm just trying to join the two and am getting the following error:

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

I don't really know where to go from here.


回答1:


You aren't setting the value at that key to anything, so Python thinks you're trying to read the key instead. The date_dict dictionary is empty.

You need to be setting a value, so something like this:

date_dict[date] = filename

A dictionary has keys and values. To assign to the dictionary, you would do something like this:

date_dict['key'] = value

There is no problem with the join section. '{0} {1}'.format(filename,date) is fine, although you might want an underscore instead of a space. Or maybe a dash if this is going to go on a website.

Related question about KeyError

Edit

Based on our discussion, I think you need to do this:

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


来源:https://stackoverflow.com/questions/33112471/creating-a-dictionary-while-iterating-through-multiple-for-loops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!