Last active
February 6, 2024 13:33
-
-
Save wrabit/75c9359755e16923beed6a149a3210c5 to your computer and use it in GitHub Desktop.
Laravel inspired data_get() for python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def data_get(data, path, default=None): | |
""" | |
Retrieves a value from a nested data structure using "dot" notation. | |
This function is designed to work with dictionaries and tuples. | |
Parameters | |
---------- | |
data : dict or tuple or None | |
The data structure from which to retrieve the value. | |
This can be a nested dictionary, tuple, or a combination of both. | |
path : str | |
The "dot" notation path to the value to be retrieved. | |
For dictionaries, parts of the path are treated as keys. | |
For tuples, parts of the path are treated as indices. | |
For example, the path 'user.0' would get the first element from the 'user' key if it's a tuple. | |
default : any, optional | |
The default value to return if the specified path is not found in the data structure. | |
By default, it is None. | |
Returns | |
------- | |
any | |
The value found at the specified path in the data structure. | |
If the path is not found, the default value is returned. | |
Examples | |
-------- | |
# Nested dictionary example | |
data = {'user': {'name': {'first': 'John', 'last': 'Doe'}}} | |
print(data_get(data, 'user.name.first')) # Outputs: John | |
# Tuple example | |
data = ('John', 'Doe') | |
print(data_get(data, '0')) # Outputs: John | |
# Mixed example | |
data = {'user': ('John', 'Doe')} | |
print(data_get(data, 'user.0')) # Outputs: John | |
""" | |
parts = path.split(".") | |
for part in parts: | |
if isinstance(data, dict): | |
data = data.get(part, default) | |
elif isinstance(data, tuple) and part.isdigit(): | |
index = int(part) | |
if index < len(data): | |
data = data[index] | |
else: | |
return default | |
elif hasattr(data, part): # Check if data has the attribute | |
data = getattr(data, part) # Get the attribute | |
else: | |
return default | |
return data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment