Python字典是地圖。用方括號,我們分配和訪問一個鍵的值。用get()我們可以指定一個默認結果。python字典錯誤正在發生中
但爲什麼會發生這種情況?
cu = {}
for p in soup.find_all('p'):
parent = p.findParent()
if parent not in cu.keys():
cu[parent]=[]
cu[parent].append(p)
for key in cu.keys():
bolok = '<div class="test">'
for block in cu[key]:
bolok += str(block)
bolok+='</div>'
cu[key][0].replace_with(soup.new_tag('test'))
>> cu.keys()[0]
>> <div class="inner">\n<span class="icon major fa-cloud"></span>\n<h1>Hi, I'm <strong>Photon</strong>, another fine<br/>\r\n\t\t\t\t\tlittle freebie from <a href="http://html5up.net">HTML5 UP</a>.</h1>\n<div></div>\n<ul class="actions">\n<li><a class="button scrolly" href="#one">Discover</a></li>\n</ul>\n</div>
>> cu[cu.keys()[0]]
>> Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: <div class="inner">\n<span class="icon major fa-cloud"></span>\n<h1>Hi, I'm <strong>Photon</strong>, another fine<br/>\r\n\t\t\t\t\tlittle freebie from <a href="http://html5up.net">HTML5 UP</a>.</h1>\n<div></div>\n<ul class="actions">\n<li><a class="button scrolly" href="#one">Discover</a></li>\n</ul>\n</div>
這不能在python 3中工作。您可以提供[mcve]。請不要使用'dict'作爲你的變量。 –
請注意,'dict'已經意味着Python中的某些東西。 – Iluvatar
'dict.keys()'沒有意義。你需要一個'dict'的實例,它保存着'keys()' –