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

Time:11-05

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.

CodePudding user response:

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