dictor: An Elegant Dictionary and JSON Handler
Dictor is a Python JSON and Dictionary (Hash, Map) handler. It takes a dictionary or JSON data and returns a value for a specific key, simplifying access to deeply nested structures. Its primary goal is to eliminate the need for repetitive `try/except` blocks when performing lookups and to provide flexible fallback values for missing keys. The current version is 0.1.12, with new releases typically driven by feature additions or bug fixes rather than a strict cadence.
Warnings
- breaking Dictor versions 0.1.13 and up will drop support for Python 2. Users on Python 2 must remain on version 0.1.12 or earlier.
- gotcha If a dictionary key contains a literal dot ('.') character (e.g., `'my.key'`), `dictor` will by default interpret it as a path separator, potentially leading to `None` or an incorrect value. For example, `dictor({'my.key': 'value'}, 'my.key')` will return `None` because it tries to find a nested `key` within `my`.
- gotcha When `checknone=True` is passed to `dictor`, it will raise a `ValueError` if the value found at the specified path is `None`. This can lead to unexpected program termination if `None` is a valid intermediate value.
- gotcha The `rtype` argument, used to cast the return value to a specific type (e.g., `int`, `str`), only applies to scalar values. If the value found at the specified path is a complex data structure (like a dictionary, list, or tuple), it will be returned as is, regardless of the `rtype` specified.
Install
-
pip install dictor
Imports
- dictor
from dictor import dictor
Quickstart
import json
from dictor import dictor
data = {
"characters": {
"Lonestar": {
"id": 55923,
"role": "renegade",
"items": ["space winnebago", "leather jacket"]
},
"Barfolomew": {
"id": 55924,
"role": "mawg",
"items": ["peanut butter jar", "waggy tail"]
}
}
}
# Accessing a nested value using dot notation
lonestar_role = dictor(data, "characters.Lonestar.role")
print(f"Lonestar's role: {lonestar_role}")
# Accessing a non-existent key with a fallback default value
dark_helmet_role = dictor(data, "characters.Dark Helmet.role", default="villain")
print(f"Dark Helmet's role: {dark_helmet_role}")
# Accessing an item from a list by index
first_lonestar_item = dictor(data, "characters.Lonestar.items.0")
print(f"First item for Lonestar: {first_lonestar_item}")