在列表/字典中搜索错误

时间:2015-11-03 05:33:31

标签: python list dictionary

我编写了一个网络抓取工具,它将货币交换值作为嵌套列表返回,我正在尝试编写一部分代码,该代码将在此列表中搜索给定名称并提取与其关联的货币值数据。< / p>

我的记录功能看起来像

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

并且该函数应该能够搜索“Argentine Peso”等货币名称并返回

[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

1 个答案:

答案 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)是有争议的,这使得它无法转换为可用的货币字典索引

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()