Home > front end >  Safely get nested list index from json?
Safely get nested list index from json?

Time:03-08

I know how to safely get keys from json using .get()

data = {"person": {"name": "chris", "age": 11, "interests": []}}

data.get("person", {}).get("height") would just return None

But what if I wanted to do the same with a list?

data.get("person", {}).get("interests", []).get([3], {}).get("someotherdata")

How do I assume the list index exists and carry on safely if it doesn't?

Obviously I could just try getting the list and checking its length before trying to get the index, but is there not a cleaner way?

Chris

CodePudding user response:

You can use match-case:

data = {"person": {"name": "chris", "age": 11, "interests": []}}
match data:
   case {"person": {"interests": [_, _, _, val, *_]}}:
      print(val)
   case _: #default case, only executes no match is made
      pass

Here, the case block attempts to match a nested dictionary containing the keys "person" and "interests", and then provides a match if the "interests" key has a corresponding list with an index of three.

In the example above, nothing will be printed, since the list value for "interests" is empty. However, if "interests" has an index of 3, 4 will be printed:

data = {"person": {"name": "chris", "age": 11, "interests": [1, 2, 3, 4]}}
match data:
  case {"person": {"interests": [_, _, _, val, *_]}}:
     print(val)
  case _:
     pass

Output:

4

Edit: purely inline solution:

r = v[3] if len(v:=data.get('person', {}).get('interests', [])) > 3 else {}
  • Related