python - Create a dictionary from list items -


the following code gives me output displayed below. take each of numbers following respective category , put them dictionary. efficient way so?

current code:

d = {} data = []  contentb = tree.xpath("//table[@class='yfnc_tabledata1']/tr[1]/td/table/tr/td")  in contentb:     = a.text_content().strip()     data.extend(a.splitlines())  item in data:      if re.match(r'\(\d+', item) not none:         item = item.replace('(', '-').replace(')', '')          print(item) 

output

period ending total revenue 31821000 30871000 29904000 cost of revenue 16447000 16106000 15685000 gross profit 15374000 14765000 14219000 operating expenses research development 1770000 1715000 1634000 

desired outcome

{     'total revenue': [31821000, 30871000, 29904000],     'cost of revenue': [16447000, 16106000, 15685000],     'gross profit': [15374000, 14765000, 14219000] } 

similar @eugene soldatov's answer, i've tried automatically identify data breaks. i'm using locale package though since data seems use commas separating units. may have adjust second line locale. untested because don't use locale formatting ;-)

import locale #locale.setlocale(locale.lc_all, 'en_us.utf8')  summary = {} current_key = none line in data:     try         if current_key:             summary[current_key].append(locale.atoi(line.strip()))     except valueerror:         current_key = line.strip()         summary[current_key] = [] 

Comments

Popular posts from this blog

javascript - Google App Script ContentService downloadAsFile not working -

javascript - Function overwritting -

php - Find a regex to take part of Email -