Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract specific value from nested Json when key is known but exact location is not

I have the following JSON object in python:

[<OpenAIObject at 0x1d9902d9f40> JSON: {
   " Easy": -0.012022864,
   " Hard": -4.432567
 },
 <OpenAIObject at 0x1d9902e10e0> JSON: {
   " Text": -6.827632e-08,
   " Video": -15.946914
 },
 <OpenAIObject at 0x1d9902e1630> JSON: {
   " ": 0,
   " .": -17.975779
 }

I know that somewhere in the JSON (nested in the second level) will be the key " Easy" and I would like to extract the value for that key. However, it will not always be in the same position (it will be in the same level).

Is there any more elegant way to extract the value rather than simply looping over the entire object, using a logic statement to find the key, and then extracting the value? It seems like there would be a single line of code that could accomplish this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here is a one-liner to extract all " Easy" values from your dict :

KEY = " Easy"

d = {
    1: {" Easy": -0.012022864, " Hard": -4.432567},
    2: {" Text": -6.827632e-08, " Video": -15.946914},
    3: {" ": 0, " .": -17.975779},
}

values = list(map(lambda kv: kv[1][KEY], filter(lambda kv: KEY in kv[1], d.items())))
print(values)
# [-0.012022864]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading