This is a part of the code where you scrape the data from a website.I have scraped "a" tag and "span" tag from table tag and I have displayed the output of it which can be seen below.
for item in contents:
data = [] # list for single table
for tr in item.find_all('tr')[1:]: # find rows in table - skip row with headers `[1:]`
a = tr.find('a') # get only from first column
a = a.text.strip()
span = tr.find('span') # get only from first column
span = span.text.strip()
data.append( (a, span) )
print(data)
tables.append(data)
for name, table in zip(names, tables):
print('-', name)
for a, span in table:
print(a, span)
When you print "tables":
[[('GE', 'General Electric Co'), ('T', 'AT&T Inc'), ('BAC', 'Bank of America Corp'), ('AMD', 'Advanced Micro Devices Inc'), ('CMCSA', 'Comcast Corp'), ('M', "Macy's Inc"), ('PFE', 'Pfizer Inc'), ('F', 'Ford Motor Co'), ('WU', 'Western Union Co'), ('CSCO', 'Cisco Systems Inc')], [('BBY', 'Best Buy Co Inc'), ('UA', 'Under Armour Inc'), ('CMG', 'Chipotle Mexican Grill Inc'), ('UAA', 'Under Armour Inc'), ('ABMD', 'Abiomed Inc'), ('HRL', 'Hormel Foods Corp'), ('INTU', 'Intuit Inc'), ('DISCK', 'Discovery Inc'), ('DISCA', 'Discovery Inc'), ('CBRE', 'CBRE Group Inc')], [('DLTR', 'Dollar Tree Inc'), ('HPE', 'Hewlett Packard Enterprise Co'), ('XEC', 'Cimarex Energy Co'), ('HP', 'Helmerich and Payne Inc'), ('MCK', 'McKesson Corp'), ('IRM', 'Iron Mountain Inc'), ('CTL', 'Centurylink Inc'), ('COG', 'Cabot Oil & Gas Corp'), ('CAH', 'Cardinal Health Inc'), ('NTAP', 'NetApp Inc')]]
The actual output of the entire code is(when you print(a,span)):
- Most Actives
GE General Electric Co
T AT&T Inc
BAC Bank of America Corp
AMD Advanced Micro Devices Inc
CMCSA Comcast Corp
M Macy's Inc
PFE Pfizer Inc
F Ford Motor Co
WU Western Union Co
CSCO Cisco Systems Inc
- Gainers
BBY Best Buy Co Inc
UA Under Armour Inc
CMG Chipotle Mexican Grill Inc
UAA Under Armour Inc
ABMD Abiomed Inc
HRL Hormel Foods Corp
INTU Intuit Inc
DISCK Discovery Inc
DISCA Discovery Inc
CBRE CBRE Group Inc
I want to convert this to dictionary where if user enters "GE" ,the output will be "General Electric Co" ans so on.
aandspanwhen you want to construct a dictionary? Just load the dictionary in a loop rather than printing the key, value pairs.table. Is it a dictionary already?d = {k:v for k,v in zip(names, tables)}? It is hard to know for sure without a minimal reproducible example. which includesnames,tablesand intended output.