Dotty Dict
Dotty Dict is a Python library that provides a dictionary-like object for quick access to deeply nested keys using dot notation. It wraps standard Python dictionaries and supports various dictionary operations including creation, reading, updating, and deleting nested keys. The current stable version is 1.3.1, released in July 2022, suggesting a moderate release cadence.
Warnings
- gotcha Integer keys in string paths are automatically treated as list indices. For example, `dot['items.0.name']` accesses the 'name' key of the first item in the 'items' list. If you intend to use an integer as a dictionary key, it will be interpreted as a list index.
- gotcha Dictionary keys cannot contain dots (`.`) by default. If a key genuinely contains a dot, it will be interpreted as a path separator, leading to unexpected nested dictionary structures.
- gotcha Dotty Dict does not support attribute-style access (e.g., `data.user.address.street`). All access to nested keys must be done using dictionary-style item access with string paths (e.g., `data['user.address.street']`).
- gotcha Boolean type keys are only partially supported. Accessing boolean keys directly (e.g., `dot[True]`) works, but using them within a dot-notation string path might lead to unexpected behavior or errors.
- gotcha In very rare edge cases, when a nested dictionary contains two keys of different types but with the same value (e.g., an integer key and a string key both representing '1'), `dotty-dict` might return a dict or list under a 'random' key with the passed value, leading to inconsistent behavior.
Install
-
pip install dotty-dict
Imports
- dotty
from dotty_dict import dotty
- Dotty
from dotty_dict import Dotty
Quickstart
from dotty_dict import dotty
# Create a new dotty dict
data = dotty()
data['user.address.street'] = 'Main St'
data['user.address.city'] = 'Anytown'
data['items.0.name'] = 'Laptop'
data['items.0.price'] = 1200
print(f"Street: {data['user.address.street']}")
print(f"First item name: {data['items.0.name']}")
# Wrap an existing dictionary
existing_dict = {'product': {'details': {'id': 'P101', 'stock': 50}}}
dot_wrapper = dotty(existing_dict)
print(f"Product ID: {dot_wrapper['product.details.id']}")
dot_wrapper['product.details.stock'] = 45
print(f"Updated existing dict: {existing_dict}") # The underlying dict is modified