是否有OrderedDict理解?

时间:2015-10-01 19:45:32

标签: python beautifulsoup

我不知道是否有这样的事情 - 但我正在努力做一个有序的字典理解。但它似乎不起作用?

import requests
from bs4 import BeautifulSoup
from collections import OrderedDict


soup = BeautifulSoup(html, 'html.parser')
tables = soup.find_all('table')
t_data = OrderedDict()
rows = tables[1].find_all('tr')
t_data = {row.th.text: row.td.text for row in rows if row.td }

现在它仍然是正常的词典理解(我也遗漏了对汤样板的通常要求)。 有什么想法吗?

1 个答案:

答案 0 :(得分:52)

您无法直接使用OrderedDict进行理解。但是,您可以在OrderedDict的构造函数中使用生成器。

尝试使用此尺寸:

import requests
from bs4 import BeautifulSoup
from collections import OrderedDict


soup = BeautifulSoup(html, 'html.parser')
tables = soup.find_all('table')
rows = tables[1].find_all('tr')
t_data = OrderedDict((row.th.text, row.td.text) for row in rows if row.td)
相关问题