簡體   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