Extract nested value from json-like dict by providing sequence of keys
Project description
>>> extract_nested_value({1: {2: {3: "value"}}}, [1, 2, 3])
"value
Extracts a nested value from a JSON-like dict by specifying a sequence of keys.
May be useful to avoid a KeyError exception when accessing JSON-like dicts with a dynamic nested structure, when you know the key paths of elements, but are unsure whether elements exist.
Returns the nested value or None if it wasn't found. Could throw a KeyError exception if strict=True
is passed.
Examples
>>> extract_nested_value({1: 2}, [1])
2
>>> extract_nested_value({1: {2: {3: "value"}}}, [1, 2, 3])
"value"
>>> extract_nested_value({1: 2}, ["a"])
None
>>> extract_nested_value({1: 2}, [])
{1: 2}
>>> extract_nested_value({1: 2}, ["a"], strict=True)
KeyError: "Keys sequence '["a"]' do not exists in object '{1: 2}'")
Arguments
from_obj
: JSON-like dict from which the nested value should be extractedkeys
: ordered sequence of keys to derive the nested valuestrict
: (defaultFalse
) prevents throwing an exception when keys are not exist in nested object when set toFalse
. ThrowsKeyError
exception if set toTrue
and key wasn't found.
Returns
Nested value, if the entire chain of keys is present, or None
Development
Look at Makefile
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
Built Distribution
File details
Details for the file nested-value-extractor-0.1.1.tar.gz
.
File metadata
- Download URL: nested-value-extractor-0.1.1.tar.gz
- Upload date:
- Size: 3.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.11.5
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 57653d3f60300106d4b7e35341f33e4b8aa5e9ec0186ae8059595d13f884c542 |
|
MD5 | 52019540a41d606e39e5677fdbd40cae |
|
BLAKE2b-256 | fbd49ecc570c0d0e2568a7707221a0aa151fb5e89bb71060500b676cf29524d5 |
File details
Details for the file nested_value_extractor-0.1.1-py3-none-any.whl
.
File metadata
- Download URL: nested_value_extractor-0.1.1-py3-none-any.whl
- Upload date:
- Size: 3.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.11.5
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 46c1b93dbbc4517715f846b21de2f6a508989fd50db81ee6d99ca14043e7b354 |
|
MD5 | 6e0bbc5b6c1b1c5becc5930f8d63e50e |
|
BLAKE2b-256 | 266125bdf9a1b6a7a76d8c2c3720e038078b04fc5b6e234c361a02071100bbcd |