将多个值循环到字典中

2024-05-19 01:08:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我想就先前提出的一个问题展开讨论:

Nested For Loop with Unequal Entities

在这个问题上,我请求了一个方法来提取位置的类型(医院、紧急护理等)以及位置的名称(WELLSTAR ATLANTA医疗中心、WELLSTAR ATLANTA医疗中心南部等)。你知道吗

答案建议使用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)

我想扩展现有的解决方案,以包括实体的地址与适当的键值组合匹配。如果最好的解决办法是使用字典以外的东西,我也愿意接受这个建议。你知道吗


Tags: fromimporturlforget字典中心requests
2条回答

假设您有一个dictd = {'Name': 'Zara', 'Age': 7},现在您想添加另一个值

'Sex'= 'female'

您可以使用内置的更新方法。你知道吗

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

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

ref是https://www.tutorialspoint.com/python/dictionary_update.htm

假设您有一个dict my_dict,并且希望添加2,其中my_key作为键。简单地做:

my_dict['my_key'] = 2

相关问题 更多 >

    热门问题