[英]Adding to dictionary within for loop: not incrementing
本質上,我想將以下XML輸入存儲到字典中。
輸入提取(變量xml_tree )
<listingContentIndexEntry>
<active>true</active>
<lastUpdatedDate>2015-05-05</lastUpdatedDate>
<listingHomeAwayId>/listings/0000/2671f21e-16a7-45c9-a6b7-d94ca801db24</listingHomeAwayId>
<listingUrl>http://www.a.url</listingUrl>
</listingContentIndexEntry>
<listingContentIndexEntry>
<active>true</active>
<lastUpdatedDate>2015-05-05</lastUpdatedDate>
<listingHomeAwayId>/listings/0000/849302c1-8734-4540-8169-57d71a309dc8</listingHomeAwayId>
<listingUrl>http://www.a.url</listingUrl>
</listingContentIndexEntry>
<listingContentIndexEntry>
<active>true</active>
<lastUpdatedDate>2015-05-05</lastUpdatedDate>
<listingHomeAwayId>/listings/0000/7fbfa33c-3371-4850-9c21-6a7685dd0ae1</listingHomeAwayId>
<listingUrl>http://www.a.url</listingUrl>
</listingContentIndexEntry>
<listingContentIndexEntry>
<active>false</active>
<lastUpdatedDate>2015-05-05</lastUpdatedDate>
<listingHomeAwayId>/listings/0000/336b4e46-e710-49a0-a192-ab66e320fe89</listingHomeAwayId>
<listingUrl>http://www.a.url</listingUrl>
</listingContentIndexEntry>
<listingContentIndexEntry>
.........
到目前為止,我的代碼是
xml_tree = ET.fromstring(xml)
#parse xml
for listingContentIndexEntry in xml_tree.iter('listingContentIndexEntry'):
active = listingContentIndexEntry.find('active').text
lastUpdatedDate = listingContentIndexEntry.find('lastUpdatedDate').text
listingId = listingContentIndexEntry.find('listingId').text
listingUrl = listingContentIndexEntry.find('listingUrl').text
data = {'listingId':listingId,'active': active,'lastupdateDate': lastUpdatedDate}
id_dict.update(data)
數據已從XML正確讀取(我已經打印到屏幕上了),但是當我打印字典時,當應該有數百個時,它僅顯示一個條目。
{'lastupdateDate': '2015-06-23', 'listingId': '/listings/0000/c5666884-c74f-4b89-831a-e285720e611c', 'active': 'false'}
如何將多個條目添加到字典中?
dict.update
方法只是將字典的新元素添加到上一字典中,並且如果在舊字典中遇到相同的key
,還可以更新已經設置的值。
dict1 = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female', 'Age':19 }
dict1.update(dict2)
print "Value : %s" % dict1
輸出為:
Value : {'Age': 19, 'Name': 'Zara', 'Sex': 'female'}
您會在這里看到舊時代被新時代所取代。 同樣,在您的代碼中,未設置新keys
,始終會更新先前設置的鍵。 如果你想獲得的所有結果做出改變id_dict
到id_list
列表,並使用id_list.append(data)
insted的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.