python-benedict
The Python dictionary for humans dealing with evil/complex data.
Features
- Full keypath support (using the dot syntax by default)
- Easy I/O operations with most common formats:
base64,json,query-string,toml,yaml,xml - Many utility and parse methods to retrieve data as needed (all methods listed below)
- Give benediction :) to
dictvalues before they are returned (they receive benedict casting) - 100% backward-compatible (you can replace existing dicts without pain)
Requirements
- Python 2.7, 3.4, 3.5, 3.6, 3.7
Installation
- Run
pip install python-benedict
Testing
- Run
tox/python setup.py test
Usage
benedict is a dict subclass, so it is possible to use it as a normal dictionary (you can just cast an existing dict).
Import
from benedict import benedict
Init
Create a new instance:
d = benedict()
... or cast an existing dict:
d = benedict(existing_dict)
If the existing dict keys contain the keypath separator a ValueError will be raised.
In this case you should need to use a custom keypath separator.
Keypath
. is the default keypath separator.
d = benedict()
# set values by keypath
d['profile.firstname'] = 'Fabio'
d['profile.lastname'] = 'Caccamo'
print(d) # -> { 'profile':{ 'firstname':'Fabio', 'lastname':'Caccamo' } }
print(d['profile']) # -> { 'firstname':'Fabio', 'lastname':'Caccamo' }
# check if keypath exists in dict
print('profile.lastname' in d) # -> True
# delete value by keypath
del d['profile.lastname']
Custom keypath separator
You can customize the keypath separator passing the keypath_separator argument in the constructor.
d = benedict(existing_dict, keypath_separator='/')
API
Keypath methods
# Return a list of all keypaths in the dict.
d.keypaths()
I/O methods
These methods simplify I/O operations with most common formats: base64, json, query-string, toml, yaml, xml
# Try to load/decode a json encoded string and return it as dict instance.
# Accept as first argument: url, filepath or string.
# A ValueError is raised in case of failure.
benedict.from_json(s)
# Return the dict instance encoded in json format and optionally save it at the specified filepath.
# It's possible to pass custom options to the encoder using kwargs, eg. sort_keys=True.
# A ValueError is raised in case of failure.
s = d.to_json(filepath='', **kwargs)
# Try to load/decode a yaml encoded string and return it as dict instance.
# Accept as first argument: url, filepath or string.
# A ValueError is raised in case of failure.
benedict.from_yaml(s)
# Return the dict instance encoded in yaml format and optionally save it at the specified filepath.
# It's possible to pass custom options to the encoder using kwargs.
# A ValueError is raised in case of failure.
s = d.to_yaml(filepath='', **kwargs)
Utility methods
These methods are common utilities that will speed up your everyday work.
# Clean the current dict removing all empty values: None, '', {}, [], ().
# If strings, dicts or lists flags are False, related empty values will not be deleted.
d.clean(strings=True, dicts=True, lists=True)
# Return a clone (deepcopy) of the dict.
d.clone()
# Return a readable representation of any dict/list.
# This method can be used both as static method or instance method.
s = benedict.dump(d.keypaths())
print(s)
# or
d = benedict()
print(d.dump())
# Return a filtered dict using the given predicate function.
# Predicate function receives key, value arguments and should return a bool value.
predicate = lambda k, v: v is not None
d.filter(predicate)
# Return a flatten dict using the given separator to concat nested dict keys.
d.flatten(separator='_')
# Merge one or more dictionary objects into current instance (deepupdate).
# Sub-dictionaries keys will be merged toghether.
d.merge(a, b, c)
# Remove multiple keys from the dict.
d.remove(['firstname', 'lastname', 'email'])
# Return a dict subset for the given keys.
d.subset(['firstname', 'lastname', 'email'])
Parse methods
These methods are wrappers of the get method, they parse data trying to return it in the expected type.
# Get value by key or keypath trying to return it as bool.
# Values like `1`, `true`, `yes`, `on`, `ok` will be returned as `True`.
d.get_bool(key, default=False)
# Get value by key or keypath trying to return it as list of bool values.
# If separator is specified and value is a string it will be splitted.
d.get_bool_list(key, default=[], separator=',')
# Get value by key or keypath trying to return it as datetime.
# If format is not specified it will be autodetected.
# If options and value is in options return value otherwise default.
d.get_datetime(key, default=None, format=None, options=[])
# Get value by key or keypath trying to return it as list of datetime values.
# If separator is specified and value is a string it will be splitted.
d.get_datetime_list(key, default=[], format=None, separator=',')
# Get value by key or keypath trying to return it as Decimal.
# If options and value is in options return value otherwise default.
d.get_decimal(key, default=Decimal('0.0'), options=[])
# Get value by key or keypath trying to return it as list of Decimal values.
# If separator is specified and value is a string it will be splitted.
d.get_decimal_list(key, default=[], separator=',')
# Get value by key or keypath trying to return it as dict.
# If value is a json string it will be automatically decoded.
d.get_dict(key, default={})
# Get email by key or keypath and return it.
# If value is blacklisted it will be automatically ignored.
# If check_blacklist is False, it will be not ignored even if blacklisted.
d.get_email(key, default='', options=None, check_blacklist=True)
# Get value by key or keypath trying to return it as float.
# If options and value is in options return value otherwise default.
d.get_float(key, default=0.0, options=[])
# Get value by key or keypath trying to return it as list of float values.
# If separator is specified and value is a string it will be splitted.
d.get_float_list(key, default=[], separator=',')
# Get value by key or keypath trying to return it as int.
# If options and value is in options return value otherwise default.
d.get_int(key, default=0, options=[])
# Get value by key or keypath trying to return it as list of int values.
# If separator is specified and value is a string it will be splitted.
d.get_int_list(key, default=[], separator=',')
# Get value by key or keypath trying to return it as list.
# If separator is specified and value is a string it will be splitted.
d.get_list(key, default=[], separator=',')
# Get list by key or keypath and return value at the specified index.
# If separator is specified and list value is a string it will be splitted.
d.get_list_item(key, index=0, default=None, separator=',')
# Get phone number by key or keypath and return a dict with different formats (e164, international, national).
# If country code is specified (alpha 2 code), it will be used to parse phone number correctly.
d.get_phonenumber(key, country_code=None, default=None)
# Get value by key or keypath trying to return it as slug.
# If options and value is in options return value otherwise default.
d.get_slug(key, default='', options=[])
# Get value by key or keypath trying to return it as list of slug values.
# If separator is specified and value is a string it will be splitted.
d.get_slug_list(key, default=[], separator=',')
# Get value by key or keypath trying to return it as string.
# Encoding issues will be automatically fixed.
# If options and value is in options return value otherwise default.
d.get_str(key, default='', options=[])
# Get value by key or keypath trying to return it as list of str values.
# If separator is specified and value is a string it will be splitted.
d.get_str_list(key, default=[], separator=',')
Django
benedict could be very useful in django views too:
params = benedict(request.GET.items())
License
Released under MIT License.
Release files for python-benedict 0.7.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| python-benedict-0.7.0.tar.gz | 12.6 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| python_benedict-0.7.0-py2-none-any.whl | Python 2 | none | any | Details |
Total release size: 27.6 kB
Release files / python-benedict-0.7.0.tar.gz
| Download URL | python-benedict-0.7.0.tar.gz |
|---|---|
| Size | 12.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a11e1ffe7fea1bb230af1ffde1e179388a2d89c1d329761ba5a90c2329ee90e8
|
|
BLAKE2b-256 checksum How to use checksums |
2ac58164a69eeee30ddd655636a0e4576ccb889c77cdb8acbb1350d6c8c98fb9
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.1 CPython/3.6.3
|
Release files / python_benedict-0.7.0-py2-none-any.whl
| Download URL | python_benedict-0.7.0-py2-none-any.whl |
|---|---|
| Size | 15.0 kB |
| Tags | Python 2 |
|
SHA-256 checksum How to use checksums |
2dcab86cd0d74c6d26179c57bdb8a9dd8fd0c5bd261e369972371a2c8ec0403f
|
|
BLAKE2b-256 checksum How to use checksums |
f1f2bb6ee8c88063b534ba137e74f2ac66e4b69e6a67e2c34f2bf6d59d28166d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.1 CPython/3.6.3
|