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?
Intent signaling: If you use OrderedDict over dict , then your code makes it clear that the order of items in the dictionary is important. You're clearly communicating that your code needs or relies on the order of items in the underlying dictionary.
The OrderedDict is a subclass of dict object in Python. The only difference between OrderedDict and dict is that, in OrderedDict, it maintains the orders of keys as inserted. In the dict, the ordering may or may not be happen. The OrderedDict is a standard library class, which is located in the collections module.
An OrderedDict is a dictionary subclass in which the order of the content added is maintained.
An OrderedDict is a dictionary subclass that remembers the order in which its contents are added. import collections print 'Regular dictionary:' d = {} d['a'] = 'A' d['b'] = 'B' d['c'] = 'C' d['d'] = 'D' d['e'] = 'E' for k, v in d. items(): print k, v print '\nOrderedDict:' d = collections.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With