【问题标题】:Python: Trying to extract a value from a list of dictionaries that is stored as a stringPython: Trying to extract a value from a list of dictionaries that is stored as a string
【发布时间】:2022-12-02 07:13:44
【问题描述】:

I am getting data from an API and storing it in json format. The data I pull is in a list of dictionaries. I am using Python. My task is to only grab the information from the dictionary that matches the ticker symbol.

This is the short version of my data printing using json dumps

[
    {
        "ticker": "BYDDF.US",
        "name": "BYD Co Ltd-H",
        "price": 25.635,
        "change_1d_prc": 9.927101200686117
    },
    {
        "ticker": "BYDDY.US",
        "name": "BYD Co Ltd ADR",
        "price": 51.22,
        "change_1d_prc": 9.843448423761526
    },
    {
        "ticker": "TSLA.US",
        "name": "Tesla Inc",
        "price": 194.7,
        "change_1d_prc": 7.67018746889343
    }
]

Task only gets the dictionary for ticker = TSLA.US. If possible, only get the price associated with this ticker.

I am unaware of how to reference "ticker" or loop through all of them to get the one I need.

I tried the following, but it says that its a string, so it doesn't work:

   if "ticker" == "TESLA.US":
        print(i)

【问题讨论】:

    标签: python json api


    【解决方案1】:

    Try (mylist is your list of dictionaries)

    for entry in mylist:
        print(entry['ticker'])
    

    Then try this to get what you want:

    for entry in mylist:
        if entry['ticker'] == 'TSLA.US':
            print(entry)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-02
      • 2022-12-02
      • 1970-01-01
      • 2022-12-02
      • 2022-12-27
      • 2022-07-14
      相关资源
      最近更新 更多