Home > front end >  Python: Trying to extract a value from a list of dictionaries that is stored as a string
Python: Trying to extract a value from a list of dictionaries that is stored as a string

Time:12-02

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)

CodePudding user response:

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.

CodePudding user response:

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