This gist provides a Python equivalent of Lodash's _.get() function implemented as a lambda expression. The function safely accesses nested object properties using a dot-separated string or array path, returning a default value if the path is invalid.
get=lambda obj,path,default=None:(lambda x:default if x is None else x)((lambda p:next(((obj[int(A[0])]if A[0].isdigit()and isinstance(obj,list)else obj.get(A[0],default))if len(A)==1 else get(obj[int(A[0])]if A[0].isdigit()and isinstance(obj,list)else obj.get(A[0],{}),A[1:],default)for A in[path.split('.')if isinstance(path,str)else path]),default))(path))The get function takes three parameters:
obj: The object to query (e.g., a nested dictionary).path: The path to the property, either as a dot-separated string (e.g.,'a.b.c') or an array (e.g.,['a', 'b', 'c']).default: The value to return if the path is invalid or the property isNone(defaults toNone).
obj = {
'a': {
'b': {
'c': 123
}
}
}
# String path
print(get(obj, 'a.b.c')) # Output: 123
print(get(obj, 'a.b.d', 'not found')) # Output: 'not found'
# Array path
print(get(obj, ['a', 'b', 'c'])) # Output: 123
print(get(obj, ['a', 'b', 'd'], 'not found')) # Output: 'not found'
# Non-existent path
print(get(obj, 'x.y.z', 'not found')) # Output: 'not found'- Path Handling: Converts a string path (e.g.,
'a.b.c') to a list by splitting on dots, or uses the provided list path directly. - Recursive Access: Uses
dict.get()to safely access each path segment:- If only one segment remains, returns the value or the default.
- If multiple segments remain, recursively calls
geton the nested object (or an empty dict if the key is missing).
- Default Value: Ensures the final result returns the default value if the resolved value is
None.
- Basic Functionality: This is a simplified implementation compared to Lodash's
_.get(). It assumes the object is a dictionary and doesn't handle advanced cases like:- Array indices (e.g.,
a[0].b). - Special characters in keys.
- Non-dictionary objects in the path.
- Array indices (e.g.,
- Performance: The lambda-based approach may be less performant for deeply nested objects compared to a traditional function.
- Edge Cases: Does not handle all edge cases as robustly as the full Lodash library.
For production use, consider using a library like python-lodash or a more robust recursive function.
This code was created to replicate Lodash's _.get() behavior in Python using a concise lambda expression, avoiding unsafe methods like eval(). It fixes issues like KeyError by using dict.get() and provides a functional, single-line solution.
This code is provided under the MIT License. Feel free to use, modify, and distribute it as needed.
This implementation was created by Grok, built by xAI.