skip to Main Content

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)

3

Answers


  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)
    
    Login or Signup to reply.
  2. This is a solution that I’ve seen divide the python community. Some say that it’s a feature and "very pythonic"; others say that it’s a bad design choice we’re stuck with now, and bad practice. I’m personally not a fan, but it is a way to solve this problem, so do with it what you will. 🙂

    Python function loops aren’t a new scope; the loop variable persists even after the loop. So, either of these are a solution. Assuming that your list of dictionaries is stored as json_dict:

    for target_dict in json_dict:
        if target_dict["ticker"] == "TESLA.US":
            break
    

    At this point, target_dict will be the dictionary you want.

    Login or Signup to reply.
  3. It is possible to iterate through a list of dictionaries using a for loop.

        for stock in list:
            if stock["ticker"] == "TSLA.US":
                return stock["price"]
    
    

    This essentially loops through every item in the list, and for each item (which is a dictionary) looks for the key "ticker" and checks if its value is equal to "TSLA.US". If it is, then it returns the value associated with the "price" key.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search