有OrderedDict理解吗? [英] Is there an OrderedDict comprehension?

查看:65
本文介绍了有OrderedDict理解吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否有这样的事情-但我正在尝试进行有序的dict理解.但是它似乎不起作用吗?

I don't know if there is such a thing - but I'm trying to do an ordered dict comprehension. However it doesn't seem to work?

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 }

目前,这是普通的字典理解(我也没有将通常的要求留给汤样板). 有什么想法吗?

It's left as a normal dict comprehension for now (I've also left out the usual requests to soup boilerplate). Any ideas?

推荐答案

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

You can't directly do a comprehension with an OrderedDict. You can, however, use a generator in the constructor for 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)

这篇关于有OrderedDict理解吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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