2016-09-23 69 views
-1

我想對以前提出的問題展開:循環多個值到字典

Nested For Loop with Unequal Entities

在這個問題,我要求的方法來提取位置的類型(醫院,緊急護理等)在除了地點的名稱(WELLSTAR亞特蘭大醫療中心,WELLSTAR亞特蘭大南部醫療中心等)。

答案建議使用for循環和字典來收集值和鍵。代碼片段如下所示:

from pprint import pprint 

import requests 
from bs4 import BeautifulSoup 

url = "https://www.wellstar.org/locations/pages/default.aspx" 
response = requests.get(url) 
soup = BeautifulSoup(response.content, "html.parser") 

d = {} 
for row in soup.select(".WS_Content > .WS_LeftContent > table > tr"): 
title = row.h3.get_text(strip=True) 
d[title] = [item.get_text(strip=True) for item in row.select(".PurpleBackgroundHeading a)] 

pprint(d) 

我想擴展現有解決方案以包含與適當的鍵值組合匹配的實體地址。如果最好的解決方案是利用字典之外的其他東西,我也會接受這個建議。

+0

雖然涉及到前一個問題,[不要讓這一個適當的問題以及](http://stackoverflow.com/help/how-to-ask)。 –

回答

1

比方說,你有一個字典my_dict,你想添加2my_key作爲關鍵。簡單地做:

my_dict['my_key'] = 2 
0

讓說你有一個字典d = {'Name': 'Zara', 'Age': 7}現在要添加其他值

「性別」 =「女」

您可以使用內置的更新方法。

d.update({'Sex': 'female' }) 
print "Value : %s" % d 

Value : {'Age': 7, 'Name': 'Zara', 'Sex': 'female'} 

裁判是https://www.tutorialspoint.com/python/dictionary_update.htm