.read()
呼び出しの結果は辞書ではなく、文字列です。
>>> import urllib2
>>> currency = "EURO"
>>> req = urllib2.urlopen('http://rate-exchange.appspot.com/currency?from=USD&to='+ currency +'')
>>> result = req.read()
>>> result
'{"to": "EURO", "rate": 0.76810814999999999, "from": "USD"}'
>>> type(result)
<type 'str'>
結果はJSONでエンコードされたdictのように見えるので、次のようなものを使用できます
>>> import json, urllib2
>>> currency = "EURO"
>>> url = "http://rate-exchange.appspot.com/currency?from=USD&to=" + currency
>>> response = urllib2.urlopen(url)
>>> result = json.load(response)
>>> result
{u'to': u'EURO', u'rate': 0.76810815, u'from': u'USD'}
>>> type(result)
<type 'dict'>
>>> result["rate"]
0.76810815
>>> type(result["rate"])
<type 'float'>
from
[や などのパラメーターの追加を処理するより良い方法があると思いますが、URL の構成をそのままにしておいたことに注意してくださいto
。また、状況によっては、コンバージョン率を に変換しても意味がないことに注意してくださいint
。]