繁体   English   中英

将多个值循环到字典中

[英]Looping multiple values into dictionary

我想扩展之前提出的一个问题:

具有不等实体的嵌套 For 循环

在那个问题中,除了位置名称(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)

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

假设您有一个 dict my_dict并且您想以my_key作为键添加2 简单地做:

my_dict['my_key'] = 2

假设你有一个 dict 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM