EasyDict for Python Dictionaries
EasyDict is a Python library that enables accessing dictionary values as attributes, providing a JavaScript-like dot notation for Python dictionaries. It works recursively for nested structures, making dictionary manipulation more convenient and readable. The current version is 1.13, and the library receives updates periodically, with several releases each year to address bugs and introduce minor enhancements.
Warnings
- gotcha EasyDict is primarily designed for string keys when using dot notation. Attempting to access non-string keys (e.g., integers) as attributes will result in an AttributeError. You must use standard dictionary bracket notation for non-string keys.
- gotcha EasyDict recursively converts nested dictionaries and lists of dictionaries into EasyDict instances. This can sometimes lead to unexpected behavior if strict Python dict/list types are expected at certain levels, or if dealing with self-referencing dictionary structures, which can cause `RecursionError`.
- breaking In versions prior to 1.12, tuples assigned as values within an EasyDict could be incorrectly converted to lists. This could alter data structures unintentionally.
- breaking The `.pop()` and `.update()` methods had incorrect behavior in versions prior to 1.9, particularly when dealing with EasyDict instances.
Install
-
pip install easydict
Imports
- EasyDict
from easydict import EasyDict
Quickstart
from easydict import EasyDict
# Create an EasyDict from a dictionary
data = EasyDict({
'settings': {
'debug': True,
'api_key': 'abc123xyz'
},
'users': [
{'id': 1, 'name': 'Alice'},
{'id': 2, 'name': 'Bob'}
]
})
# Access values using dot notation
print(f"Debug mode: {data.settings.debug}")
print(f"API Key: {data.settings.api_key}")
print(f"First user's name: {data.users[0].name}")
# Set new attributes or modify existing ones
data.settings.debug = False
data.new_feature = {'enabled': True}
print(f"New debug mode: {data.settings.debug}")
print(f"New feature enabled: {data.new_feature.enabled}")
# EasyDict still behaves like a dict
print(f"All keys: {list(data.keys())}")