Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an OrderedDict comprehension?

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?

like image 886
Yunti Avatar asked Oct 01 '15 19:10

Yunti


People also ask

When should I use OrderedDict?

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.

What is the difference between OrderedDict and dictionary in Python?

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.

What is an OrderedDict?

An OrderedDict is a dictionary subclass in which the order of the content added is maintained.

What is collections OrderedDict?

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.


1 Answers

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) 
like image 157
Morgan Thrapp Avatar answered Sep 23 '22 05:09

Morgan Thrapp