简体   繁体   English

如何仅从所有键中拉出某些项目?

[英]How to pull only certain items from all the keys?

I am pulling from the Alpha Vantage API. 我从Alpha Vantage API中提取。 If I only want to pull the closing price from this dictionary for all the days. 如果我只想整天从这本词典中得出收盘价。 What do I do? 我该怎么办? I don't want to print but I want to save a new dictionary that only has the closing price: 我不想打印,但是我想保存一个只有收盘价的新字典:

{
    "Meta Data": {
        "1. Information": "Daily Prices (open, high, low, close) and Volumes",
        "2. Symbol": "MSFT",
        "3. Last Refreshed": "2018-09-28",
        "4. Output Size": "Compact",
        "5. Time Zone": "US/Eastern"
    },
    "Time Series (Daily)": {
        "2018-09-28": {
            "1. open": "114.1900",
            "2. high": "114.5700",
            "3. low": "113.6800",
            "4. close": "114.3700",
            "5. volume": "21647811"
        },
        "2018-09-27": {
            "1. open": "114.7800",
            "2. high": "114.9100",
            "3. low": "114.2000",
            "4. close": "114.4100",
            "5. volume": "19091299"
        },
        "2018-09-26": {
            "1. open": "114.4700",
            "2. high": "115.0550",
            "3. low": "113.7400",
            "4. close": "113.9800",
            "5. volume": "19352025"
        },
        "2018-09-25": {
            "1. open": "114.8000",
            "2. high": "115.1000",
            "3. low": "113.7500",
            "4. close": "114.4500",
            "5. volume": "22668014"
        },

Here, the dict argument is what you get from the API. 在这里,dict参数是您从API获得的。 This will return {'2018-09-28': ('114.1900', '114.3700'), '2018-09-27': ('114.7800', '114.4100'), '2018-09-26': ('114.4700', '113.9800'), '2018-09-25': ('114.8000', '114.4500')} If you don't understand something or want help please feel free to ask in the comments. 这将返回{'2018-09-28': ('114.1900', '114.3700'), '2018-09-27': ('114.7800', '114.4100'), '2018-09-26': ('114.4700', '113.9800'), '2018-09-25': ('114.8000', '114.4500')}如果您听不懂或需要帮助,请随时在评论中提问。

def getCloseOpen(alphaAPI):
    days = alphaAPI["Time Series (Daily)"]
    targData = {}
    for day,data in days.items():
        targData[day] = (data["1. open"],data["4. close"])
    return targData

You can use a dictionary comprehension and dict.items . 您可以使用字典理解和dict.items Since you are dealing with numeric data, you will likely also want to convert to float . 由于要处理数字数据,因此您可能还希望转换为float Given an input dictionary d : 给定输入字典d

closes_dict = {k: float(v['4. close']) for k, v in d['Time Series (Daily)'].items()}

{'2018-09-28': 114.37,
 '2018-09-27': 114.41,
 '2018-09-26': 113.98,
 '2018-09-25': 114.45}

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

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