Skip to main content
 首页 » 编程设计

python之在 Python 中将字符串转换为字典

2025年05月04日26cyq1162

这是从网站上抓取数据的代码的一部分。我从表格标签中抓取了“a”标签和“span”标签,并显示了它的输出,如下所示。

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) 

打印“表格”时:

[[('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')]] 

整个代码的实际输出是(当你打印(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 

我想将其转换为字典,如果用户输入“GE”,输出将是“General Electric Co”等等。

请您参考如下方法:

繁荣:

return_dict = {} 
 
for name, table in zip(names, tables): 
    print('-', name) 
    for a, span in table: 
        return_dict[a] = span 

最好有一个样本来测试它,但我认为这可以满足您的要求!

编辑

既然您已经发布了更多代码,那么这将是一个更好的答案:

return_dict = {} 
 
for a, span in tables: 
    return_dict[a] = span 

或更简洁:

return_dict = {a:span for a, span in tables} 

这些在技术上是一样的,后者只是对前者的理解。