Easy access to elements of collection/object structures
Project description
Motivating example
animals = [
{
'name': 'Wombat',
'avg_properties': {
'height': {'value': 66, 'unit': 'cm'},
'length':{'value': 108, 'unit': 'cm'},
'weight': {'value': 27, 'unit': 'kg'}
}
},
{
'name': 'Duck',
'avg_properties': {
'height': {'value': 62, 'unit': 'cm'},
'weight': {'value': 1, 'unit': 'kg'}
}
},
{
'name': 'Dog',
'max_properties': {
'height': {'value': 95, 'unit': 'cm'},
'weight': {'value': 105, 'unit': 'kg'}
}
},
]
Let's query that above structure:
for animal in animals:
print(animal["name"],
'average length',
animal["avg_properties"]["length"]["value"])
This code will abort with error as no the Duck
has no length
key. We have to add one more check.
for animal in animals:
print(animal["name"],
'average length',
animal["avg_properties"]["length"]["value"]
if "length" in animal["avg_properties"]
else '-')
This improved code will still fail as Dog
has only max_property
key, we have to handle this situation too.
for animal in animals:
if "avg_properties" in animal
and "length" in animal["avg_properties"]:
print(animal["name"],
'average length',
animal["avg_properties"]["length"]["value"])
else:
print(animal["name"],
'avarage length',
"-")
The above scenarios can be simplified by quickpath
:
from quickimport import getpath
for animal in animals:
print(animal["name"],
'average length',
getpath(animal,
("avg_properties", "length", "value"),
default='-'))
Alternatively, the keys can be represented as a single string:
from quickimport import getpaths
for animal in animals:
print(animal["name"],
'average length',
getpaths(animal,
"avg_properties.length.value"),
default='-'))
Separator can be changed to any alternative characters:
from quickimport import getpaths
for animal in animals:
print(animal["name"],
'average length',
getpaths(animal,
"avg_properties/length/value"),
default='-',
sep='/')
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
quickpath-0.9.2.tar.gz
(6.0 kB
view hashes)
Built Distribution
Close
Hashes for quickpath-0.9.2-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | d5de5d7195cbb5db299977a6a31aa7764a1e3b008beb3c337471c968be4b9be4 |
|
MD5 | ca703b1a65a9e2372fa078b1996d048d |
|
BLAKE2b-256 | 11179833bd3def69f5ab52fefd15fae7e73e1fba0e5cf3f89fb16df1671713f3 |