Home > Back-end >  How to read nested dictionary created from pandas?
How to read nested dictionary created from pandas?

Time:09-17

I am creating a dictionary from a panda table for fast access. However, I am unable to figure out how to access the elements and the key easily.

The dictionary is in the below format.

{'token': {'NIFTY22SEP2214100PE': '52263_NFO', 'NIFTY22SEP2214050PE': '52249_NFO'}, 
'o185': {'NIFTY22SEP2214100PE': True, 'NIFTY22SEP2214050PE': False}, 
'underlying': {'NIFTY22SEP2214100PE': 'NIFTY', 'NIFTY22SEP2214050PE': 'NIFTY'}, 
'instrument': {'NIFTY22SEP2214100PE': 'OPTIDX', 'NIFTY22SEP2214050PE': 'OPTIDX'}, 
'strike': {'NIFTY22SEP2214100PE': 14100, 'NIFTY22SEP2214050PE': 14050}} 

Now I want to get the 'strike' for token value '52263_NFO'. Or if I want the 'token' value for 'NIFTY22SEP2214050PE' if only o185 is True.

How can I achieve that? I know I can split this into key, item and then again in key, item and then use list comprehension.

But wanted to know if there is a more elegant solution for this.

CodePudding user response:

If your dictionary is called "dic", one thing you can do is :

token = [token for token in dic["token"] if dic["token"][token] == "52263_NFO"][0]

strike = dic["strike"][token]

You can adapt this lines for the 2nd question.

  • Related