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

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

问题描述

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

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 }

它现在作为普通的 dict 理解(我也忽略了对汤样板的通常要求).有什么想法吗?

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天全站免登陆