Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中向字典添加元素_Python_Python 2.7_Dictionary - Fatal编程技术网

在Python中向字典添加元素

在Python中向字典添加元素,python,python-2.7,dictionary,Python,Python 2.7,Dictionary,我使用了BeautifulSoup解析器来解析xml文档。下面是代码。我想把所有的元素放在一本字典里 import requests from bs4 import BeautifulSoup f = open('/home/soundarya/Desktop/mv-v18-1526.nxml','r') d = BeautifulSoup(f.read()) s = d.find('journal-meta') j = s.findAll('journal-id') print s.

我使用了BeautifulSoup解析器来解析xml文档。下面是代码。我想把所有的元素放在一本字典里

import requests
from bs4 import BeautifulSoup 

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

d = BeautifulSoup(f.read())

s = d.find('journal-meta')

j = s.findAll('journal-id')
print s.find('journal-title').renderContents()

print s.find('issn').renderContents()

print s.find('publisher-name').renderContents()

for x in j:
    print x.renderContents()
我得到了作为元素的输出:

/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**
我试着使用类似: 我得到这个错误:

AttributeError: 'dict' object has no attribute 'find'
帮我把这些元素放到字典里

a['journal-id'] = a.find('journal-id')
我想您想使用变量
d

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

一般来说,尽量使用更具描述性的变量名。

这很有效,非常感谢。知道如何将字典作为json字符串吗?你的意思是,如何将dict序列化为json<代码>导入json;json_str=json.dumps(您的dict)获取此错误:raise TypeError(repr(o)+“不是json可序列化的”)TypeError:Molecular Vision不是json可序列化的dict应该只包含一个。确保dict的键是字符串,值是str、unicode、int、long、float、bool、None。非常感谢。。我得到了它。我现在有个问题。我正在解析一个xml文档。。通过指定元数据实体,如a={}a['journal-meta']=d.find('journal-meta').renderContents()a['journal-id']=d.find('journal-id').renderContents(),如下所示。xml文档中有很多元素。是否仍然可以动态解析xml文档并获取数据?期待您的回复。谢谢
a['journal-id'] = d.find('journal-id')