简体   繁体   English

遍历字典以创建列表

[英]Iterating through dictionary to create lists

I have a dictionary, which I want to use to get data from a website and then store a separate value for each key in the dictionary with data coming from a corresponding value.我有一个字典,我想用它从网站获取数据,然后为字典中的每个键存储一个单独的值,数据来自相应的值。 The code works but only returns the data from the last key:value pair in the dictionary, instead of all of them.该代码有效,但只返回字典中最后一个键:值对的数据,而不是全部。 What am I missing?我错过了什么?

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)

You have overriden the variable "tenors".您已经覆盖了变量“tenors”。 Try to define another variable like "date", you will get your results:尝试定义另一个变量,如“日期”,你会得到你的结果:

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

So a couple things not sure why the variable is called tenor and not date but it should be singular.所以有几件事不确定为什么变量被称为男高音而不是日期,但它应该是单数。 Link should also be singluar.链接也应该是单数的。 You can use a dictionary to access by date later on, otherwise the date information is lost.您可以稍后使用字典按日期访问,否则日期信息将丢失。

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'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM