pythonlist

Extracting values from a list/dictionary?


I'm very very new to python and am trying to build an algo trading program. I have reached a point where I cannot extract a value I need from an output that looks like this:

{'stat': 'Ok', 'values': [{'exch': 'NFO', 'token': '35013', 'tsym': 'BANKNIFTY27NOV24F', 'dname': 'BANKNIFTY NOV FUT', 'optt': 'XX', 'instname': 'FUTIDX', 'pp': '2', 'ls': '15', 'ti': '0.05'}, {'exch': 'NFO', 'token': '35025', 'tsym': 'BANKNIFTY24DEC24F', 'weekly': 'W4', 'dname': 'BANKNIFTY DEC FUT', 'optt': 'XX', 'instname': 'FUTIDX', 'pp': '2', 'ls': '15', 'ti': '0.05'}, {'exch': 'NFO', 'token': '35012', 'tsym': 'BANKNIFTY29JAN25F', 'dname': 'BANKNIFTY JAN FUT', 'optt': 'XX', 'instname': 'FUTIDX', 'pp': '2', 'ls': '15', 'ti': '0.05'}]}

I'm trying to extract the value of 'token' but cannot do it. I have only tried extracting the data with some method (not sure if that is the correct term to use here) itertools but obviously, it didn't work.

Can someone please help with this?


Solution

  • load the dict as a variable "data" then extract the values for the key "values"

    iterate over the resulting list to get each dict and getthe value for the key "token"

    values = data["values"]
    
    for item in values:
        print(item["token"])
    

    which provides:

    35013
    35025
    35012