在Python中向字典添加元素

时间:2015-10-08 10:45:16

标签: python python-2.7 dictionary

我使用BeautifulSoup解析器来解析xml文档。这是下面的代码。我想把所有元素都放到一个字典中。

/usr/local/lib/python2.7/dist-packages/bs4/__init__.py:166: UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("lxml"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.

To get rid of this warning, change this:

 BeautifulSoup([your markup])

to this:

 BeautifulSoup([your markup], "lxml")

  markup_type=markup_type))
**Molecular Vision
1090-0535
Molecular Vision
Mol Vis
Mol. Vis
MV**

我得到了这个元素的输出:

import requests
from bs4 import BeautifulSoup 

f = open('/home/soundarya/Desktop/mv-v18-1526.nxml','r')

d = BeautifulSoup(f.read())

a = {}
a['journal-meta'] = d.find('journal-meta')
a['journal-id'] = a.find('journal-id')
a['journal-title'] = a.find('journal-title').renderContents()
a['issn'] = a.find('issn').renderContents()
a['publisher-name'] = a.find('publisher-name').renderContents()

for x in a:
    print x.renderContents()

我尝试使用like:

AttributeError: 'dict' object has no attribute 'find'

我收到此错误:

template <typename T>
struct MyClassT : public MyClass, public T
{
    typename std::enable_if<has_func_method<T>::value, void>::type Method()
    {
        T::Method();
    }

    typename std::enable_if<!has_func_method<T>::value, void>::type Method()
    {
        //do nothing
    }
};

帮我把元素放在字典中。

1 个答案:

答案 0 :(得分:4)

a['journal-id'] = a.find('journal-id')

我认为你想使用变量d

a['journal-id'] = d.find('journal-id')

通常,尝试使用更具描述性的变量名称。