Is there an OrderedDict comprehension?

Yunti picture Yunti · Oct 1, 2015 · Viewed 9.7k times · Source

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?

Answer

Morgan Thrapp picture Morgan Thrapp · Oct 1, 2015

You can't directly do a comprehension with an OrderedDict. You can, however, use a generator in the constructor for OrderedDict.

Try this on for size:

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)