遍历字典以创建列表

时间:2019-11-23 19:05:01

标签: python list dictionary

我有一个字典,我想用它从网站上获取数据,然后为字典中的每个键存储一个单独的值,数据来自相应的值。该代码有效,但仅返回字典中最后一个key:value对的数据,而不是全部返回的数据。我想念什么?

import csv
import requests

URL = {'Nov18': 'https://markets.cboe.com/us/futures/market_statistics/historical_data/products/csv/VX/2018-11-21',
       'Dec18': 'https://markets.cboe.com/us/futures/market_statistics/historical_data/products/csv/VX/2018-12-19'}

for tenors, links in URL.items():
    with requests.Session() as s:
        download = s.get(links)

        decoded_content = download.content.decode('utf-8')

        cr = csv.reader(decoded_content.splitlines(), delimiter=',')
        tenors = list(cr)

2 个答案:

答案 0 :(得分:0)

您已覆盖变量“ tenors”。尝试定义另一个变量,例如“ date”,您将得到结果:

import csv
import requests

URL = {'Nov18': 'https://markets.cboe.com/us/futures/market_statistics/historical_data/products/csv/VX/2018-11-21',
         'Dec18': 'https://markets.cboe.com/us/futures/market_statistics/historical_data/products/csv/VX/2018-12-19'}

tenors = []

for date, links in URL.items():
    with requests.Session() as s:
        download = s.get(links)

        decoded_content = download.content.decode('utf-8')

        cr = csv.reader(decoded_content.splitlines(), delimiter=',')
        tenors.append(list(cr))

答案 1 :(得分:0)

因此,有两点不能确定为什么将变量称为tenor而不是date,但应将其称为单数。链接也应该是唯一的。您可以稍后使用字典按日期访问,否则日期信息将丢失。

import csv
import requests

URL = {'Nov18': 'https://markets.cboe.com/us/futures/market_statistics/historical_data/products/csv/VX/2018-11-21',
     'Dec18': 'https://markets.cboe.com/us/futures/market_statistics/historical_data/products/csv/VX/2018-12-19'}

output = {}
for trade_date, link in URL.items():
    with requests.Session() as s:
        download = s.get(link)

        decoded_content = download.content.decode('utf-8')

        cr = csv.reader(decoded_content.splitlines(), delimiter=',')
        output[trade_date]= list(cr)

print(output['Nov18'])
print(output['Dec18'])