2015-08-22 110 views
0

我是新的python,我試圖實現一個小的bellman-ford算法。我從不同的貨幣在一個JSON一些速度看起來就像是:從json獲取元素

{"USD_JPY": "88.1911719", "USD_USD": "1.0000000", "JPY_EUR": "0.0086441", "BTC_USD": "122.5311820", "JPY_BTC": "0.0000923", "USD_EUR": "0.6695743", "EUR_USD": "1.2624079", "EUR_JPY": "129.3438373", "JPY_USD": "0.0111120", "BTC_BTC": "1.0000000", "EUR_BTC": "0.0110526", "BTC_JPY": "12543.0532689", "JPY_JPY": "1.0000000", "BTC_EUR": "90.3821109", "EUR_EUR": "1.0000000", "USD_BTC": "0.0071458"} 

我試圖讓實例我的對象,方式,但它似乎不能正常工作,即使它會工作,我認爲這不是真正有效(如果貨幣的變化,我的順序螺絲)

def __init__ (self, rates):  
    res = json.load(rates) 
    self.EURToEUR = 1.000000 
    self.USDToUSD = 1.000000 
    self.JPYToJPY = 1.000000 
    self.BTCToBTC = 1.000000 
    self.EURToUSD = json[6]['EUR_USD'] 
    self.EURToJPY = json[7]['EUR_JPY'] 
    self.EURToBTC = json[10]['EUR_BTC'] 
    self.USDToEUR = json[5]['USD_EUR'] 
    self.USDToBTC = json[15]['USD_BTC'] 
    self.USDToJPY = json[0]['USD_JPY'] 
    self.BTCToEUR = json[13]['BTC_EUR'] 
    self.BTCToJPY = json[11]['BTC_JPY'] 
    self.BTCToUSD = json[3]['BTC_USD'] 
    self.JPYToEUR = json[2]['JPY_EUR'] 
    self.JPYToUSD = json[8]['JPY_USD'] 
    self.JPYToBTC = json[4]['JPY_BTC'] 

如果你們能告訴我它是如何工作和閱讀我的JSON的有效辦法,我會很高興。

回答

2

您不需要使用索引訪問json對象。關鍵是你需要的一切。另外,您要訪問res,這是你的對象,你裝,不json,該模塊的這個

self.EURToUSD = res['EUR_USD']

INSEAD的名字:

self.EURToUSD = json[6]['EUR_USD']

+0

我得到以下錯誤:self.EURToUSD = JSON [ 'EUR_USD'] TypeError:'模塊'對象沒有屬性'__getitem__' – mel

+0

哦嘗試使用'self.EURToUSD = res ['EUR_USD']' – joeya17

+0

這是工作謝謝 – mel

1

有關使用collection.namedtuple如何?

from collections import namedtuple 

data = {"USD_JPY": "88.1911719", "USD_USD": "1.0000000", "JPY_EUR": "0.0086441", "BTC_USD": "122.5311820", "JPY_BTC": "0.0000923", "USD_EUR": "0.6695743", "EUR_USD": "1.2624079", "EUR_JPY": "129.3438373", "JPY_USD": "0.0111120", "BTC_BTC": "1.0000000", "EUR_BTC": "0.0110526", "BTC_JPY": "12543.0532689", "JPY_JPY": "1.0000000", "BTC_EUR": "90.3821109", "EUR_EUR": "1.0000000", "USD_BTC": "0.0071458"} 
Currency = namedtuple('Currency', data.keys()) 
currency = Currency(**data) 

那麼你得到你的數據是這樣的:

>>> currency.USD_JPY 
'88.1911719' 
>>>> currency.USD_USD 
'1.0000000' 

所以,在你例子,這將是:

def __init__ (self, data):  
    Currency = namedtuple('Currency', data.keys()) 
    self.currency = Currency(**data)