Home > front end >  How to access specific value of a nested dictionary when the key is unknown?
How to access specific value of a nested dictionary when the key is unknown?

Time:05-09

Say I have the following nested dictionary:

dict1 =  {"relatedUnderlyingInformation": {"SP500":{
                                            "underlying": "SP500",
                                            "ticker": "SPY",
                                            "balls": "S&P Index",
                                            "balls2": "I like meat"}
        }
}

If I just want to print the nested dictionary key value for balls2 ("I like meat") without knowing the key, how can I do this? I have tried the following methods and they both don't work:

print(
list(dict1.values())[0][0][3]
)

and

print(
dict1[0][0][3]
)

thank you!

CodePudding user response:

A recursive solution:

>>> dict1 =  {"relatedUnderlyingInformation": {"SP500":{
...                                             "underlying": "SP500",
...                                             "ticker": "SPY",
...                                             "balls": "S&P Index",
...                                             "balls2": "I like meat"}
...         }
... }
>>> def get_last_value(d):
...     if not isinstance(d, dict):
...         return d
...     return get_last_value(list(d.values())[-1])
...
>>> get_last_value(dict1)
'I like meat'

CodePudding user response:

I know this looks messy.


dict1 =  {"relatedUnderlyingInformation": {"SP500":{
                                            "underlying": "SP500",
                                            "ticker": "SPY",
                                            "balls": "S&P Index",
                                            "balls2": "I like meat"}
        }
}

output = list(list(list(dict1.values())[0].values())[0].values())[-1]
 
print(output) # → I like meat

OR

dict1 =  {"relatedUnderlyingInformation": {"SP500":{
                                            "underlying": "SP500",
                                            "ticker": "SPY",
                                            "balls": "S&P Index",
                                            "balls2": "I like meat"}
        }
}

for a in dict1:
    for b in dict1[a]:
        output = list(dict1[a][b].values())[-1]


print(output) # → I like meat

  • Related