Jma*_*riz 2 python dictionary urllib2
我正在研究一个简单的python脚本.它使用urllib从网页读取并将其转换为字典.Web服务器输出的方式是字典,因为它使用JSON.这是我有的:
import urllib2
d = 'http://www.somewebserver.com/tools/dictionary.php?string=hello'
r = urllib2.urlopen(d)
data = r.read()
r.close()
dictionary = dict(data)
print dictionary
唯一的问题是当我运行它时我得到这个错误:
Traceback (most recent call last):
File "get.py", line 6, in getstring()
dictionary = dict(data)
ValueError: dictionary update sequence element #0 has length 20; 2 is required
我如何成功地将其变成字典?
import json
dictionary = json.loads(data)
Run Code Online (Sandbox Code Playgroud)
或者为了保存一些步骤,您可以将文件对象传递r给json.load:
dictionary = json.load(r)
Run Code Online (Sandbox Code Playgroud)