创建词典Python列表 [英] Create List of Dictionary Python

查看:108
本文介绍了创建词典Python列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从网页上获取所有 iframe

I want to get all the iframe from a webpage.

代码

site = "http://" + url
f = urllib2.urlopen(site)
web_content =  f.read()

soup = BeautifulSoup(web_content)
info = {}
content = []
for iframe in soup.find_all('iframe'):
    info['src'] = iframe.get('src')
    info['height'] = iframe.get('height')
    info['width'] = iframe.get('width')
    content.append(info)
    print(info)       

pprint(content)

print(info)

{'src': u'abc.com', 'width': u'0', 'height': u'0'}
{'src': u'xyz.com', 'width': u'0', 'height': u'0'}
{'src': u'http://www.detik.com', 'width': u'1000', 'height': u'600'}

的结果pprint(content)

[{'height': u'600', 'src': u'http://www.detik.com', 'width': u'1000'},
{'height': u'600', 'src': u'http://www.detik.com', 'width': u'1000'},
{'height': u'600', 'src': u'http://www.detik.com', 'width': u'1000'}]

为什么内容的值不对?假设我的价值与我 print(info)的价值相同。

Why is the value of the content not right? It's suppose to be the same as the value when I print(info).

推荐答案

您不是为每个iframe创建单独的字典,您只是一遍又一遍地修改相同的字典,并且在列表中继续添加对该字典的额外引用。

You are not creating a separate dictionary for each iframe, you just keep modifying the same dictionary over and over, and you keep adding additional references to that dictionary in your list.

记住,当您执行类似 content.append(info)之类的操作时,您不会制作数据副本,您只需附加一个引用数据。

Remember, when you do something like content.append(info), you aren't making a copy of the data, you are simply appending a reference to the data.

您需要为每个iframe创建一个新的字典。

You need to create a new dictionary for each iframe.

for iframe in soup.find_all('iframe'):
   info = {}
    ...

更好的是,您不需要先创建一个空字典。只需一次创建它:

Even better, you don't need to create an empty dictionary first. Just create it all at once:

for iframe in soup.find_all('iframe'):
    info = {
        "src":    iframe.get('src'),
        "height": iframe.get('height'),
        "width":  iframe.get('width'),
    }
    content.append(info)

还有其他方法完成此操作,例如迭代属性列表,或使用列表或字典解析,但是很难改进上述代码的清晰度。

There are other ways to accomplish this, such as iterating over a list of attributes, or using list or dictionary comprehensions, but it's hard to improve upon the clarity of the above code.

这篇关于创建词典Python列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆