Handling Key Retrieval from Nested Dictionaries in Python 3.10 with Variable Depth
I'm maintaining legacy code that I'm prototyping a solution and I'm working with a nested dictionary in Python 3.10, and I'm trying to retrieve values from keys that may exist at varying depths. For instance, I have a dictionary structured as follows: ```python data = { 'user_1': { 'name': 'Alice', 'details': { 'age': 30, 'location': 'Wonderland' } }, 'user_2': { 'name': 'Bob', 'details': { 'age': 25, 'location': None } } } ``` I want to create a function that retrieves the `location` for a given user, but I want it to gracefully handle cases where the key might not exist at all or is `None`. Here's what I've tried so far: ```python def get_location(user_id): try: return data[user_id]['details']['location'] except KeyError: return 'Location not found' ``` However, if the `location` is `None`, I would still like to differentiate between a missing key and a valid key with a `None` value. I attempted to modify my function like this: ```python def get_location(user_id): user_details = data.get(user_id) if user_details and 'details' in user_details: location = user_details['details'].get('location') if location is None: return 'Location is None' return location return 'User not found' ``` While this works for checking `None`, I still want to check for the existence of the `location` key before checking its value. I'm running into an scenario where if the dictionary structure changes in the future, I might end up with `KeyErrors` again. What would be the best practice to handle this in a more robust way, possibly using recursion or a more dynamic approach? Any suggestions on improving my solution would be greatly appreciated! I'd be grateful for any help. The project is a web app built with Python. Cheers for any assistance!