36

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?

Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67
Yunti
  • 6,761
  • 12
  • 61
  • 106
  • 1
    No, there's no such thing as an OrderedDict comprehension, you just get a regular dictionary. The fact that you've previously assigned an OrderedDict to that name is irrelevant. – jonrsharpe Oct 01 '15 at 19:48
  • There is no such thing as creating an empty dict and then adding elements to it with a dict comp with an OrderedDict or any dict, once you rebind the name `t_data` it no longer points to your OrderedDict – Padraic Cunningham Oct 01 '15 at 20:10

1 Answers1

78

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)
Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67