python字典错误正在发生中

问题描述:

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> 
+2

这不能在python 3中工作。您可以提供[mcve]。请不要使用'dict'作为你的变量。 –

+2

请注意,'dict'已经意味着Python中的某些东西。 – Iluvatar

+0

'dict.keys()'没有意义。你需要一个'dict'的实例,它保存着'keys()' –

是绝对没有理由要做到这一点

>>> d={'uu':55} 
>>> d[d.keys()[0]] 
55 

除非你(无意)修改你的字典同时

编辑 感谢编辑你的问题。

,你首先应该使用defaultdict,你不会有初始化空列表:

from collections import defaultdict 
cu = defaultdict(list) 
for p in soup.find_all('p'): 
    parent = p.findParent() 
    cu[parent].append(p) 

然后,如果你不需要他们不遍历键,尝试values

for blocks in cu.values(): 
    bolok = '<div class="test">' 
    for block in blocks: 
     bolok += str(block) 
    bolok += '</div>' 
    blocks[0].replace_with(soup.new_tag('test')) 
+0

兴奋,但它does.those字符串实际上是bs4对象。键是父元素,值是子元素。可能与编码或某事有关? –

+1

值得注意的是'd.keys()[0]'在Python 3中不起作用,因为字典视图不支持索引 –

+0

确定,所以键不是字符串,而是BeautifulSoup对象?你能告诉我一个你如何构建字典的例子吗? – Saksow

你正在使用哪个python版本。请使用python 2检查以下示例。

cu = {"""<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>""":1} 
cu[cu.keys()[0]]