Python FOR循环应该产生多个结果,但只产生一个

Python FOR循环应该产生多个结果,但只产生一个,python,list,dictionary,rss,iteration,Python,List,Dictionary,Rss,Iteration,我试图从使用feedparser库获取的RSS数据字典中提取非常特定的元素,然后将该数据放入一个新字典中,以便以后可以使用Flask调用它。我这样做的原因是因为原始词典包含了大量我不需要的元数据 我已经把这个过程分解为几个简单的步骤,但是一直在为创建新词典而烦恼!正如下面所示,它确实创建了一个dictionary对象,但它并不全面——它只包含一篇文章的标题、URL和描述——其余的都没有 我尝试过切换到其他RSS源,结果也一样,所以问题可能是我尝试的方式,或者是feedparser生成的列表结构有

我试图从使用
feedparser
库获取的RSS数据字典中提取非常特定的元素,然后将该数据放入一个新字典中,以便以后可以使用
Flask
调用它。我这样做的原因是因为原始词典包含了大量我不需要的元数据

我已经把这个过程分解为几个简单的步骤,但是一直在为创建新词典而烦恼!正如下面所示,它确实创建了一个dictionary对象,但它并不全面——它只包含一篇文章的标题、URL和描述——其余的都没有

我尝试过切换到其他RSS源,结果也一样,所以问题可能是我尝试的方式,或者是
feedparser
生成的列表结构有问题

这是我的密码:

from html.parser import HTMLParser
import feedparser

def get_feed():
    url = "http://thefreethoughtproject.com/feed/"
    front_page = feedparser.parse(url)
    return front_page

feed = get_feed()

# make a dictionary to update with the vital information
posts = {}

for i in range(0, len(feed['entries'])):
    posts.update({
        'title': feed['entries'][i].title,
        'description': feed['entries'][i].summary,
        'url': feed['entries'][i].link,
    })

print(posts)
最后,我希望有一本如下所示的词典,只是它能继续收录更多的文章:

[{'Title': 'Trump Does Another Ridiculous Thing', 
  'Description': 'Witnesses looked on in awe as the Donald did this thing', 
  'Link': 'SomeNewsWebsite.com/Story12345'}, 
{...}, 
{...}] 

有些东西告诉我这是一个简单的错误——可能语法不正确,或者我忘记了一个小而重要的细节

您提供的代码示例对同一个dict进行了一次又一次的
更新。所以,在循环结束时,你只得到一个dict。您的示例数据显示,您实际上需要一个字典列表:

# make a list to update with the vital information
posts = []

for entry in feed['entries']:
    posts.append({
        'title': entry.title,
        'description': entry.summary,
        'url': entry.link,
    })

print(posts)

似乎问题在于您使用的是dict而不是list。然后更新dict的相同键,因此每次迭代都覆盖最后添加的内容

我认为以下代码将解决您的问题:

from html.parser import HTMLParser
import feedparser

def get_feed():
    url = "http://thefreethoughtproject.com/feed/"
    front_page = feedparser.parse(url)
    return front_page

feed = get_feed()

# make a dictionary to update with the vital information
posts = []  # It should be a list


for i in range(0, len(feed['entries'])):
    posts.append({
        'title': feed['entries'][i].title,
        'description': feed['entries'][i].summary,
        'url': feed['entries'][i].link,
    })

print(posts)
如您所见,上面的代码将posts变量定义为一个列表。然后在循环中,我们将DICT添加到此列表中,因此它将为您提供所需的数据结构

我希望能帮助你解决这个问题