我想扩展之前提出的问题:
Nested For Loop with Unequal Entities
在那个问题中,除了地点名称(WELLSTAR ATLANTA MEDICAL CENTER,WELLSTAR ATLANTA MEDICAL CENTER SOUTH,等)。
答案建议使用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 :(得分:1)
我们假设你有一个词典my_dict
,并且想要2
添加my_key
作为关键。只需:
my_dict['my_key'] = 2
答案 1 :(得分:0)
假设你有一个字典d = {'Name': 'Zara', 'Age': 7}
,现在你要添加另一个值
'性'='女性'
您可以使用内置更新方法。
d.update({'Sex': 'female' })
print "Value : %s" % d
Value : {'Age': 7, 'Name': 'Zara', 'Sex': 'female'}
ref是https://www.tutorialspoint.com/python/dictionary_update.htm