Skip to main content

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 extracted
  • keys: ordered sequence of keys to derive the nested value
  • strict: (default False) prevents throwing an exception when keys are not exist in nested object when set to False. Throws KeyError exception if set to True and key wasn't found.

Returns

Nested value, if the entire chain of keys is present, or None

Development

Look at Makefile

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

nested-value-extractor-0.1.1.tar.gz (3.8 kB view details)

Uploaded Source

Built Distribution

nested_value_extractor-0.1.1-py3-none-any.whl (3.6 kB view details)

Uploaded Python 3

File details

Details for the file nested-value-extractor-0.1.1.tar.gz.

File metadata

File hashes

Hashes for nested-value-extractor-0.1.1.tar.gz
Algorithm Hash digest
SHA256 57653d3f60300106d4b7e35341f33e4b8aa5e9ec0186ae8059595d13f884c542
MD5 52019540a41d606e39e5677fdbd40cae
BLAKE2b-256 fbd49ecc570c0d0e2568a7707221a0aa151fb5e89bb71060500b676cf29524d5

See more details on using hashes here.

File details

Details for the file nested_value_extractor-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for nested_value_extractor-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 46c1b93dbbc4517715f846b21de2f6a508989fd50db81ee6d99ca14043e7b354
MD5 6e0bbc5b6c1b1c5becc5930f8d63e50e
BLAKE2b-256 266125bdf9a1b6a7a76d8c2c3720e038078b04fc5b6e234c361a02071100bbcd

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page