2015-11-03 80 views
1

我已经编写了一个网页爬虫程序,它将货币交换值作为嵌套列表返回,并且我试图编写代码的一部分来搜索给定名称并通过此列表提取货币与之相关的价值数据。在列表/字典错误内搜索

我的记录功能,看起来像

[['Argentine Peso', ['9.44195', '0.10591']], ['Australian Dollar', ['1.41824', '0.70510']] 

和功能应该是能够搜索,如“阿根廷比索”的货币名称,并返回

[9.44195,0.10591] 

如何将我去有关?

def findCurrencyValue(records, currency_name): 
    l = [[(records)]] 
    d = dict(l) 
    d[currency_name] 
    return(d) 
def main(): 
    url = "https://www.cs.purdue.edu/homes/jind/exchangerate.html" 
    records = fetch(url) 
    findCurrencyValue(records, "Argentine Peso") 
    print(findCurrencyValue) 
    print("currency exchange information is\n", records) 
main() 

,但我得到的错误

ValueError: dictionary update sequence element #0 has length 1; 2 is required 
+0

我回答到这里你的问题:http://stackoverflow.com/questions/33490506/list-dictionary-error-in-my-code/33490714#33490714你应该尝试一下。 –

+0

即时通讯不允许使用外部程序 –

回答

4

您使用了错误的数据结构。将您的嵌套列表的字典那么你可以很容易的索引根据您的货币

实施

data = [['Argentine Peso', ['9.44195', '0.10591']], ['Australian Dollar', ['1.41824', '0.70510']]] 
data_dict = dict(data) 

使用

>>> data_dict['Argentine Peso'] 
['9.44195', '0.10591'] 

更新

回来参考你的代码,哟乌尔在嵌套中的数据(record)方法contriving,这是防止它要转换为可使用的字典索引-能够按币种

l = [[(records)]] 
d = dict(l) 

>>> dict([[(data)]]) 

Traceback (most recent call last): 
    File "<pyshell#240>", line 1, in <module> 
    dict([[(data_dict)]]) 
ValueError: dictionary update sequence element #0 has length 1; 2 is required 

改变线

findCurrencyValue(records, "Argentine Peso") 

records = dict(records) 
findCurrencyValue = records["Argentine Peso"] 

和删除功能findCurrencyValue

def findCurrencyValue(records, currency_name): 
    d = dict(records) 
    return(d[currency_name]) 
def main(): 
    url = "https://www.cs.purdue.edu/homes/jind/exchangerate.html" 
    records = fetch(url) 
    curreny_value = findCurrencyValue(records, "Argentine Peso") 
    print(curreny_value) 
    print("currency exchange information is\n", records) 
main() 
+0

有没有办法做到这一点,保持我的结构? –

+0

如果解决方案对您来说似乎很难,那么答案是否定的。 – Abhijit

+0

我的意思是不能保持功能,但仍然正确地将记录更改为字典? –