Is there an OrderedDict comprehension?

前端 未结 1 430
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-03 20:05

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 imp         


        
1条回答
  •  情话喂你
    2021-01-03 20:39

    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)
    

    0 讨论(0)
提交回复
热议问题