### Clone Repository and Setup Environment Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Steps to clone the repository, create and activate a virtual environment, and install project dependencies including pre-commit hooks. ```bash git clone https://github.com/fabiocaccamo/python-benedict.git && cd python-benedict python -m venv venv && . venv/bin/activate python -m pip install --upgrade pip pip install -r requirements.txt -r requirements-test.txt pre-commit install --install-hooks ``` -------------------------------- ### Install Python Benedict main package Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Install only the core Python Benedict package. Optional requirements can be installed separately later. ```bash pip install python-benedict ``` -------------------------------- ### Install Python Benedict with all extras Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Install the main package along with all optional requirements. This command installs the base package and all additional features. ```bash pip install "python-benedict[all]" ``` -------------------------------- ### Set, Get, and Delete Values by Keypath Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Demonstrates how to set, get, check existence, and delete values using dot notation as the default keypath separator. This is useful for accessing nested dictionary elements. ```python 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"] ``` -------------------------------- ### Get List Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value and attempts to convert it to a list. If a separator is provided and the value is a string, it will be split. ```python # 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 all keypaths Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Returns a list of all keypaths in the dictionary. Set `indexes` to `True` to include list value indexes and `sort` to `True` to sort the resulting list. ```python # Return a list of all keypaths in the dict. # If indexes is True, the output will include list values indexes. # If sort is True, the resulting list will be sorted k = d.keypaths(indexes=False, sort=True) ``` -------------------------------- ### Get Dictionary Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value and attempts to convert it to a dictionary. If the value is a JSON string, it will be automatically decoded. ```python # 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 String List Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a list of string values. If a separator is provided and the value is a string, it will be split. ```python # 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=",") ``` -------------------------------- ### Get Integer List Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a list of integer values. If a separator is provided and the value is a string, it will be split. ```python # 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 as Date Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value by key or keypath, attempting to parse it as a date. Auto-detects format if not specified. Can optionally check against a list of choices. Returns a default value if not found or unparseable. ```python # Get value by key or keypath trying to return it as date. # If format is not specified it will be autodetected. # If choices and value is in choices return value otherwise default. d.get_date(key, default=None, format=None, choices=[]) ``` -------------------------------- ### Get Value as Datetime Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value by key or keypath, attempting to parse it as a datetime object. Auto-detects format if not specified. Can optionally check against a list of choices. Returns a default value if not found or unparseable. ```python # Get value by key or keypath trying to return it as datetime. # If format is not specified it will be autodetected. # If choices and value is in choices return value otherwise default. d.get_datetime(key, default=None, format=None, choices=[]) ``` -------------------------------- ### Get Value as Date List Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value by key or keypath, attempting to parse it as a list of dates. If the value is a string and a separator is provided, it will be split. Auto-detects date format if not specified. Defaults to an empty list. ```python # Get value by key or keypath trying to return it as list of date values. # If separator is specified and value is a string it will be splitted. d.get_date_list(key, default=[], format=None, separator=",") ``` -------------------------------- ### Get items sorted by keys Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Returns a list of key/value pairs sorted by keys. The `reverse` parameter can be set to `True` to reverse the order. ```python # Return items (key/value list) sorted by keys. # If reverse is True, the list will be reversed. items = d.items_sorted_by_keys(reverse=False) ``` -------------------------------- ### Get Slug List Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a list of slug values. If a separator is provided and the value is a string, it will be split. ```python # 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 Email Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves an email address. If the value is blacklisted, it is ignored by default. Set `check_blacklist` to `False` to disable this behavior. ```python # 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="", choices=None, check_blacklist=True) ``` -------------------------------- ### Get List Item Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a list by key or keypath and returns the value at a specified index. If the list value is a string and a separator is provided, it will be split first. ```python # 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 Decimal List Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a list of Decimal values. If a separator is provided and the value is a string, it will be split. ```python # 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 Datetime List Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a list of datetime values. If a separator is provided and the value is a string, it will be split. ```python # 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 Float List Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a list of float values. If a separator is provided and the value is a string, it will be split. ```python # 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 items sorted by values Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Returns a list of key/value pairs sorted by values. The `reverse` parameter can be set to `True` to reverse the order. ```python # Return items (key/value list) sorted by values. # If reverse is True, the list will be reversed. items = d.items_sorted_by_values(reverse=False) ``` -------------------------------- ### Get Value as Boolean List Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value by key or keypath, attempting to parse it as a list of booleans. If the value is a string and a separator is provided, it will be split. Defaults to an empty list. ```python # 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 dictionary subset by keys Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Returns a dictionary subset containing only the specified keys. Keys can be provided as a single key, a list, or `*args`. ```python # Return a dict subset for the given keys. # It is possible to pass a single key or more keys (as list or *args). s = d.subset(["firstname", "lastname", "email"]) ``` -------------------------------- ### Standardize dictionary keys Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Standardizes all dictionary keys, for example, converting "Location Latitude" to "location_latitude". ```python # Standardize all dict keys, e.g. "Location Latitude" -> "location_latitude". d.standardize() ``` -------------------------------- ### Get Integer Value Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value and attempts to convert it to an integer. If choices are provided and the value is in the choices, it returns the value; otherwise, it returns the default. ```python # Get value by key or keypath trying to return it as int. # If choices and value is in choices return value otherwise default. d.get_int(key, default=0, choices=[]) ``` -------------------------------- ### Get Decimal Value Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value and attempts to convert it to a Decimal. If choices are provided and the value is in the choices, it returns the value; otherwise, it returns the default. ```python # Get value by key or keypath trying to return it as Decimal. # If choices and value is in choices return value otherwise default. d.get_decimal(key, default=Decimal("0.0"), choices=[]) ``` -------------------------------- ### Get Float Value Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value and attempts to convert it to a float. If choices are provided and the value is in the choices, it returns the value; otherwise, it returns the default. ```python # Get value by key or keypath trying to return it as float. # If choices and value is in choices return value otherwise default. d.get_float(key, default=0.0, choices=[]) ``` -------------------------------- ### Get Value as Boolean Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value by key or keypath, attempting to parse it as a boolean. Recognizes common truthy values like '1', 'true', 'yes'. Defaults to False if not found or unparseable. ```python # 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) ``` -------------------------------- ### Set nested values using attribute-style access Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Allows setting nested dictionary values using attribute notation when `keyattr_dynamic` is enabled. Keys must be strings and not start with an underscore. ```python d = benedict(keyattr_dynamic=True) # default False d.profile.firstname = "Fabio" d.profile.lastname = "Caccamo" print(d) # -> { "profile":{ "firstname":"Fabio", "lastname":"Caccamo" } } ``` -------------------------------- ### Get String Value Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value and attempts to convert it to a string, automatically fixing encoding issues. If choices are provided and the value is in the choices, it returns the value; otherwise, it returns the default. ```python # Get value by key or keypath trying to return it as string. # Encoding issues will be automatically fixed. # If choices and value is in choices return value otherwise default. d.get_str(key, default="", choices=[]) ``` -------------------------------- ### Create and use Benedict instances Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Demonstrates creating empty Benedict instances, casting existing dictionaries, and initializing from data sources like URLs or Django request parameters. ```python from benedict import benedict # create a new empty instance d = benedict() # or cast an existing dict d = benedict(existing_dict) # or create from data source (filepath, url or data-string) in a supported format: # Base64, CSV, JSON, TOML, XML, YAML, query-string d = benedict("https://localhost:8000/data.json", format="json") # or in a Django view params = benedict(request.GET.items()) page = params.get_int("page", 1) ``` -------------------------------- ### Run Tests with Tox or Unittest Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Instructions for executing project tests using either tox for comprehensive testing or Python's built-in unittest module. ```bash tox python -m unittest ``` -------------------------------- ### Create Benedict Instance from URL (XML) Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Instantiate a benedict object from an XML file located at a URL. ```python # url d = benedict("https://localhost:8000/data.xml", format="xml") ``` -------------------------------- ### Create Benedict Instance from Filepath (YAML) Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Instantiate a benedict object from a YAML file. ```python # filepath d = benedict("/root/data.yml", format="yaml") ``` -------------------------------- ### Create Benedict Instance from S3 Path Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Instantiate a benedict object from a file in an S3 bucket. Requires S3 connection options. ```python # s3 d = benedict("s3://my-bucket/data.xml", s3_options={"aws_access_key_id": "...", "aws_secret_access_key": "..."}) ``` -------------------------------- ### Find Value by Keys/Keypaths Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Searches for the first matching value using a list of keys or keypaths. If no match is found, a default value is returned. ```python keys = ["a.b.c", "m.n.o", "x.y.z"] f = d.find(keys, default=0) ``` -------------------------------- ### Initialize Benedict with Custom Keypath Separator Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Shows how to initialize a Benedict dictionary with a custom keypath separator by passing the `keypath_separator` argument to the constructor. This is useful when dictionary keys might conflict with the default dot separator. ```python d = benedict(existing_dict, keypath_separator="/") ``` -------------------------------- ### Load Data from Query String Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Tries to load/decode a query-string and returns it as a benedict instance. A ValueError is raised in case of failure. ```python # Try to load/decode a query-string and return it as benedict instance. # Accept as first argument: url, filepath or data-string. # A ValueError is raised in case of failure. d = benedict.from_query_string(s, **kwargs) ``` -------------------------------- ### Input from URL with Source Restriction Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Create a benedict instance from a URL, explicitly allowing only 'url' as a source. This prevents loading from other sources like S3. ```python # url d = benedict("https://localhost:8000/data.json", sources=["url"]) # -> ok d = benedict.from_json("https://localhost:8000/data.json", sources=["url"]) # -> ok ``` -------------------------------- ### Get UUID List Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a list of valid UUID values. If a separator is provided and the value is a string, it will be split. ```python # Get value by key or keypath trying to return it as list of valid uuid values. # If separator is specified and value is a string it will be splitted. d.get_uuid_list(key, default=[], separator=",") ``` -------------------------------- ### Access List Elements by Index in Keypaths Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Demonstrates how to use list indices, including negative indices, within keypaths to access elements in nested lists. This allows for efficient retrieval of specific items within complex data structures. ```python # Eg. get last location cordinates of the first result: loc = d["results[0].locations[-1].coordinates"] lat = loc.get_decimal("latitude") lng = loc.get_decimal("longitude") ``` -------------------------------- ### Load Data from HTML Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Tries to load/decode HTML data and returns it as a benedict instance. It's possible to pass decoder specific options using kwargs. A ValueError is raised in case of failure. ```python # Try to load/decode a html data and return it as benedict instance. # Accept as first argument: url, filepath or data-string. # It's possible to pass decoder specific options using kwargs: # https://beautiful-soup-4.readthedocs.io/ # A ValueError is raised in case of failure. d = benedict.from_html(s, **kwargs) ``` -------------------------------- ### Match values by keypath pattern Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Returns a list of values whose keypath matches a given pattern (regex or string). Wildcards like `[*]` can be used for string patterns to match all list indexes. Set `indexes` to `True` to match patterns against list values. ```python # Return a list of all values whose keypath matches the given pattern (a regex or string). # If pattern is string, wildcard can be used (eg. [*] can be used to match all list indexes). # If indexes is True, the pattern will be matched also against list values. m = d.match(pattern, indexes=True) ``` -------------------------------- ### Load Data from Pickle Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Tries to load/decode pickle encoded data in Base64 format and returns it as a benedict instance. It's possible to pass decoder specific options using kwargs. A ValueError is raised in case of failure. ```python # Try to load/decode a pickle encoded in Base64 format and return it as benedict instance. # Accept as first argument: url, filepath or data-string. # It's possible to pass decoder specific options using kwargs: # https://docs.python.org/3/library/pickle.html # A ValueError is raised in case of failure. d = benedict.from_pickle(s, **kwargs) ``` -------------------------------- ### Disable keyattr functionality Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Disables the attribute-style access for getting and setting dictionary items. This can be done via the constructor or by setting the `keyattr_enabled` property. ```python d = benedict(existing_dict, keyattr_enabled=False) # default True ``` ```python d.keyattr_enabled = False ``` -------------------------------- ### get_list Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value by key or keypath and attempts to return it as a list. If a separator is provided and the value is a string, it will be split. ```APIDOC ## get_list ### Description Retrieves a value by key or keypath and attempts to return it as a list. If a separator is provided and the value is a string, it will be split. ### Method `d.get_list(key, default=[], separator=",")` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **list** (list) - The list value. #### Response Example None ``` -------------------------------- ### Get Slug Value Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value and attempts to convert it to a slug. If choices are provided and the value is in the choices, it returns the value; otherwise, it returns the default. ```python # Get value by key or keypath trying to return it as slug. # If choices and value is in choices return value otherwise default. d.get_slug(key, default="", choices=[]) ``` -------------------------------- ### get_str Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value by key or keypath and attempts to return it as a string. Encoding issues will be automatically fixed. If choices are provided and the value is in choices, it returns the value; otherwise, it returns the default. ```APIDOC ## get_str ### Description Retrieves a value by key or keypath and attempts to return it as a string. Encoding issues will be automatically fixed. If choices are provided and the value is in choices, it returns the value; otherwise, it returns the default. ### Method `d.get_str(key, default="", choices=[])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **str** (str) - The string value. #### Response Example None ``` -------------------------------- ### Load Data from TOML Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Tries to load/decode TOML encoded data and returns it as a benedict instance. It's possible to pass decoder specific options using kwargs. A ValueError is raised in case of failure. ```python # Try to load/decode a toml encoded data and return it as benedict instance. # Accept as first argument: url, filepath or data-string. # It's possible to pass decoder specific options using kwargs: # https://pypi.org/project/toml/ # A ValueError is raised in case of failure. d = benedict.from_toml(s, **kwargs) ``` -------------------------------- ### Get UUID Value Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value and attempts to convert it to a valid UUID. If choices are provided and the value is in the choices, it returns the value; otherwise, it returns the default. ```python # Get value by key or keypath trying to return it as valid uuid. # If choices and value is in choices return value otherwise default. d.get_uuid(key, default="", choices=[]) ``` -------------------------------- ### Get Phone Number Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a phone number and returns a dictionary with different formats (e164, international, national). A country code can be provided for accurate parsing. ```python # 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) ``` -------------------------------- ### Create Benedict Instance from Data String (JSON) Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Instantiate a benedict object directly from a JSON formatted string. ```python # data d = benedict('{"a": 1, "b": 2, "c": 3, "x": 7, "y": 8, "z": 9}') ``` -------------------------------- ### to_plist Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Encodes the dictionary instance into p-list format. Optionally saves the output to a file. Supports passing encoder-specific options. ```APIDOC ## to_plist ### Description Encodes the dictionary instance into p-list format. Optionally saves the output to a file. Supports passing encoder-specific options. ### Method `to_plist(**kwargs)` ### Parameters #### Query Parameters - **kwargs** - Optional - Encoder specific options (e.g., for `plistlib`). ### Response - **string** - The p-list formatted string of the dictionary. ### Error Handling - A `ValueError` is raised in case of failure. ``` -------------------------------- ### get_int_list Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value by key or keypath and attempts to return it as a list of integer values. If a separator is provided and the value is a string, it will be split. ```APIDOC ## get_int_list ### Description Retrieves a value by key or keypath and attempts to return it as a list of integer values. If a separator is provided and the value is a string, it will be split. ### Method `d.get_int_list(key, default=[], separator=",")` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **list** (list) - A list of integer values. #### Response Example None ``` -------------------------------- ### I/O Methods Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Methods for reading data from and writing data to various formats including JSON, CSV, YAML, and more. ```APIDOC ### I/O methods - [`from_base64`](#from_base64) - [`from_cli`](#from_cli) - [`from_csv`](#from_csv) - [`from_ini`](#from_ini) - [`from_html`](#from_html) - [`from_json`](#from_json) - [`from_pickle`](#from_pickle) - [`from_plist`](#from_plist) - [`from_query_string`](#from_query_string) - [`from_toml`](#from_toml) - [`from_xls`](#from_xls) - [`from_xml`](#from_xml) - [`from_yaml`](#from_yaml) - [`to_base64`](#to_base64) - [`to_csv`](#to_csv) - [`to_ini`](#to_ini) - [`to_json`](#to_json) - [`to_pickle`](#to_pickle) - [`to_plist`](#to_plist) - [`to_query_string`](#to_query_string) - [`to_toml`](#to_toml) - [`to_xml`](#to_xml) - [`to_yaml`](#to_yaml) ``` -------------------------------- ### to_query_string Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Encodes the dictionary instance into a query-string format. Optionally saves the output to a file. ```APIDOC ## to_query_string ### Description Encodes the dictionary instance into a query-string format. Optionally saves the output to a file. ### Method `to_query_string(**kwargs)` ### Parameters #### Query Parameters - **kwargs** - Optional - Additional keyword arguments. ### Response - **string** - The query-string formatted string of the dictionary. ### Error Handling - A `ValueError` is raised in case of failure. ``` -------------------------------- ### get_decimal_list Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value by key or keypath and attempts to return it as a list of Decimal values. If a separator is provided and the value is a string, it will be split. ```APIDOC ## get_decimal_list ### Description Retrieves a value by key or keypath and attempts to return it as a list of Decimal values. If a separator is provided and the value is a string, it will be split. ### Method `d.get_decimal_list(key, default=[], separator=",")` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **list** (list) - A list of Decimal values. #### Response Example None ``` -------------------------------- ### Input from S3 with Invalid Source Restriction Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Attempt to create a benedict instance from an S3 URL while restricting sources to only 'url'. This will raise a ValueError. ```python # s3 d = benedict("s3://my-bucket/data.json", sources=["url"]) # -> raise ValueError d = benedict.from_json("s3://my-bucket/data.json", sources=["url"]) # -> raise ValueError ``` -------------------------------- ### get_date Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value by key or keypath, attempting to return it as a date. Autodetects format if not specified. Can filter by a list of choices. ```APIDOC ## get_date ### Description Retrieves a value by key or keypath, attempting to return it as a date. Autodetects format if not specified. Can filter by a list of choices. ### Method `get_date(key, default=None, format=None, choices=[])` ### Parameters #### Path Parameters - **key** (string) - Required - The key or keypath to retrieve the value from. #### Query Parameters - **default** (any) - Optional - The default value to return if the key is not found or the value cannot be converted to a date. Defaults to `None`. - **format** (string) - Optional - The date format to use for parsing. If not specified, it will be autodetected. - **choices** (list) - Optional - A list of allowed date values. If the retrieved value is not in this list, the default value is returned. ``` -------------------------------- ### Load Data from PLIST Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Tries to load/decode p-list encoded data and returns it as a benedict instance. It's possible to pass decoder specific options using kwargs. A ValueError is raised in case of failure. ```python # Try to load/decode a p-list encoded data and return it as benedict instance. # Accept as first argument: url, filepath or data-string. # It's possible to pass decoder specific options using kwargs: # https://docs.python.org/3/library/plistlib.html # A ValueError is raised in case of failure. d = benedict.from_plist(s, **kwargs) ``` -------------------------------- ### to_yaml Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Encodes the dictionary instance into YAML format. Optionally saves the output to a file. Supports passing encoder-specific options. ```APIDOC ## to_yaml ### Description Encodes the dictionary instance into YAML format. Optionally saves the output to a file. Supports passing encoder-specific options. ### Method `to_yaml(**kwargs)` ### Parameters #### Query Parameters - **kwargs** - Optional - Encoder specific options (e.g., for `PyYAML`). ### Response - **string** - The YAML formatted string of the dictionary. ### Error Handling - A `ValueError` is raised in case of failure. ``` -------------------------------- ### to_pickle Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Encodes the dictionary instance into pickle format (Base64). Optionally saves the output to a file. Supports passing encoder-specific options. ```APIDOC ## to_pickle ### Description Encodes the dictionary instance into pickle format (Base64). Optionally saves the output to a file. Supports passing encoder-specific options. ### Method `to_pickle(**kwargs)` ### Parameters #### Query Parameters - **kwargs** - Optional - Encoder specific options (e.g., for `pickle`). ### Response - **string** - The Base64 encoded pickle string of the dictionary. ### Error Handling - A `ValueError` is raised in case of failure. ``` -------------------------------- ### Search dictionary items Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Searches for and returns a list of items (dictionary, key, value) matching a query. Options include searching in keys, values, exact matching, and case sensitivity. ```python # Search and return a list of items (dict, key, value, ) matching the given query. r = d.search("hello", in_keys=True, in_values=True, exact=False, case_sensitive=False) ``` -------------------------------- ### Load Data from XML Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Tries to load/decode XML encoded data and returns it as a benedict instance. It's possible to pass decoder specific options using kwargs. A ValueError is raised in case of failure. ```python # Try to load/decode a xml encoded data and return it as benedict instance. # Accept as first argument: url, filepath or data-string. # It's possible to pass decoder specific options using kwargs: # https://github.com/martinblech/xmltodict # A ValueError is raised in case of failure. d = benedict.from_xml(s, **kwargs) ``` -------------------------------- ### Load Data from XLS/XLSX/XLSM Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Tries to load/decode an XLS file (".xls", ".xlsx", ".xlsm") from a URL, filepath, or data-string. It's possible to pass decoder specific options using kwargs. A ValueError is raised in case of failure. ```python # Try to load/decode a xls file (".xls", ".xlsx", ".xlsm") from url, filepath or data-string. # Accept as first argument: url, filepath or data-string. # It's possible to pass decoder specific options using kwargs: # - https://openpyxl.readthedocs.io/ (for .xlsx and .xlsm files) # - https://pypi.org/project/xlrd/ (for .xls files) # A ValueError is raised in case of failure. d = benedict.from_xls(s, sheet=0, columns=None, columns_row=True, **kwargs) ``` -------------------------------- ### get_date_list Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value by key or keypath, attempting to return it as a list of dates. Splits string values if a separator is provided and autodetects date format. ```APIDOC ## get_date_list ### Description Retrieves a value by key or keypath, attempting to return it as a list of dates. Splits string values if a separator is provided and autodetects date format. ### Method `get_date_list(key, default=[], format=None, separator=',')` ### Parameters #### Path Parameters - **key** (string) - Required - The key or keypath to retrieve the value from. #### Query Parameters - **default** (list) - Optional - The default value to return if the key is not found or the value cannot be converted to a list of dates. Defaults to `[]`. - **format** (string) - Optional - The date format to use for parsing. If not specified, it will be autodetected. - **separator** (string) - Optional - The separator to use when splitting string values. Defaults to `,`. ``` -------------------------------- ### Load Data from CSV Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Tries to load/decode CSV encoded data and returns it as a benedict instance. It's possible to specify the columns list, default: None (in this case the first row values will be used as keys). It's possible to pass decoder specific options using kwargs. A ValueError is raised in case of failure. ```python # Try to load/decode a csv encoded data and return it as benedict instance. # Accept as first argument: url, filepath or data-string. # It's possible to specify the columns list, default: None (in this case the first row values will be used as keys). # It's possible to pass decoder specific options using kwargs: # https://docs.python.org/3/library/csv.html # A ValueError is raised in case of failure. d = benedict.from_csv(s, columns=None, columns_row=True, **kwargs) ``` -------------------------------- ### to_xml Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Encodes the dictionary instance into XML format. Optionally saves the output to a file. Supports passing encoder-specific options. ```APIDOC ## to_xml ### Description Encodes the dictionary instance into XML format. Optionally saves the output to a file. Supports passing encoder-specific options. ### Method `to_xml(**kwargs)` ### Parameters #### Query Parameters - **kwargs** - Optional - Encoder specific options (e.g., for `xmltodict`). ### Response - **string** - The XML formatted string of the dictionary. ### Error Handling - A `ValueError` is raised in case of failure. ``` -------------------------------- ### get_int Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value by key or keypath and attempts to return it as an integer. If choices are provided and the value is in choices, it returns the value; otherwise, it returns the default. ```APIDOC ## get_int ### Description Retrieves a value by key or keypath and attempts to return it as an integer. If choices are provided and the value is in choices, it returns the value; otherwise, it returns the default. ### Method `d.get_int(key, default=0, choices=[])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **int** (int) - The integer value. #### Response Example None ``` -------------------------------- ### Load Data from CLI Arguments Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Loads and decodes data from a string of CLI arguments. ArgumentParser specific options can be passed using kwargs. Returns a new dict instance. A ValueError is raised in case of failure. ```python # Load and decode data from a string of CLI arguments. # ArgumentParser specific options can be passed using kwargs: # https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser # Return a new dict instance. A ValueError is raised in case of failure. d = benedict.from_cli(s, **kwargs) ``` -------------------------------- ### to_toml Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Encodes the dictionary instance into TOML format. Optionally saves the output to a file. Supports passing encoder-specific options. ```APIDOC ## to_toml ### Description Encodes the dictionary instance into TOML format. Optionally saves the output to a file. Supports passing encoder-specific options. ### Method `to_toml(**kwargs)` ### Parameters #### Query Parameters - **kwargs** - Optional - Encoder specific options (e.g., for `toml`). ### Response - **string** - The TOML formatted string of the dictionary. ### Error Handling - A `ValueError` is raised in case of failure. ``` -------------------------------- ### get_datetime Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value by key or keypath, attempting to return it as a datetime object. Autodetects format if not specified. Can filter by a list of choices. ```APIDOC ## get_datetime ### Description Retrieves a value by key or keypath, attempting to return it as a datetime object. Autodetects format if not specified. Can filter by a list of choices. ### Method `get_datetime(key, default=None, format=None, choices=[])` ### Parameters #### Path Parameters - **key** (string) - Required - The key or keypath to retrieve the value from. #### Query Parameters - **default** (any) - Optional - The default value to return if the key is not found or the value cannot be converted to a datetime. Defaults to `None`. - **format** (string) - Optional - The datetime format to use for parsing. If not specified, it will be autodetected. - **choices** (list) - Optional - A list of allowed datetime values. If the retrieved value is not in this list, the default value is returned. ``` -------------------------------- ### Enable dynamic keyattr functionality Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Enables dynamic attribute access for creating nested dictionaries on the fly. This is controlled by the `keyattr_dynamic` option in the constructor or via its property. ```python d = benedict(existing_dict, keyattr_dynamic=True) # default False ``` ```python d.keyattr_dynamic = True ``` -------------------------------- ### get_email Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves an email by key or keypath. If the value is blacklisted, it will be ignored unless `check_blacklist` is set to `False`. ```APIDOC ## get_email ### Description Retrieves an email by key or keypath. If the value is blacklisted, it will be ignored unless `check_blacklist` is set to `False`. ### Method `d.get_email(key, default="", choices=None, check_blacklist=True)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **str** (str) - The email address. #### Response Example None ``` -------------------------------- ### Set and manipulate nested values using key lists Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Enables setting, checking existence, and deleting nested dictionary values using a list of keys as a path. This provides an alternative to dotted notation. ```python d = benedict() # set values by keys list 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 keys list del d[["profile", "lastname"]] print(d["profile"]) # -> { "firstname":"Fabio" } ``` -------------------------------- ### get_dict Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value by key or keypath and attempts to return it as a dictionary. If the value is a JSON string, it will be automatically decoded. ```APIDOC ## get_dict ### Description Retrieves a value by key or keypath and attempts to return it as a dictionary. If the value is a JSON string, it will be automatically decoded. ### Method `d.get_dict(key, default={})` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **dict** (dict) - The dictionary value. #### Response Example None ``` -------------------------------- ### Utility Methods Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Provides common utility functions for dictionary manipulation, such as cleaning, cloning, filtering, and restructuring. ```APIDOC ## Utility Methods These methods are common utilities that will speed up your everyday work. Utilities that accept key argument(s) also support keypath(s). Utilities that return a dictionary always return a new `benedict` instance. ### `clean` ```python # Clean the current dict instance removing all empty values: None, "", {}, [], (). # If strings or collections (dict, list, set, tuple) flags are False, # related empty values will not be deleted. d.clean(strings=True, collections=True) ``` ### `clone` ```python # Return a clone (deepcopy) of the dict. c = d.clone() ``` ### `dump` ```python # 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()) ``` ### `filter` ```python # 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 f = d.filter(predicate) # Use deep=True to apply the predicate recursively to all nested dicts. f = d.filter(predicate, deep=True) ``` ### `find` ```python # Return the first match searching for the given keys/keypaths. # If no result found, default value is returned. keys = ["a.b.c", "m.n.o", "x.y.z"] f = d.find(keys, default=0) ``` ### `flatten` ```python # Return a new flattened dict using the given separator to join nested dict keys to flatten keypaths. f = d.flatten(separator="_") # Return a new flattened dict also flattening list/tuple values using [i] index notation. f = d.flatten(separator="_", indexes=True) ``` ### `freeze` ```python # Make the dict immutable: any attempt to modify it will raise a TypeError. # Only top-level keys are frozen; nested dicts are not affected. d.freeze() ``` ### `frozen` ```python # Return True if the dict is frozen (immutable), False otherwise. if d.frozen: ... ``` ### `groupby` ```python # Group a list of dicts at key by the value of the given by_key and return a new dict. g = d.groupby("cities", by_key="country_code") ``` ### `invert` ```python # Return an inverted dict where values become keys and keys become values. # Since multiple keys could have the same value, each value will be a list of keys. # If flat is True each value will be a single value (use this only if values are unique). i = d.invert(flat=False) ``` ``` -------------------------------- ### get_str_list Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value by key or keypath and attempts to return it as a list of string values. If a separator is provided and the value is a string, it will be split. ```APIDOC ## get_str_list ### Description Retrieves a value by key or keypath and attempts to return it as a list of string values. If a separator is provided and the value is a string, it will be split. ### Method `d.get_str_list(key, default=[], separator=",")` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **list** (list) - A list of string values. #### Response Example None ``` -------------------------------- ### to_ini Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Encodes the dictionary instance into INI format. Optionally saves the output to a file. Supports passing encoder-specific options. ```APIDOC ## to_ini ### Description Encodes the dictionary instance into INI format. Optionally saves the output to a file. Supports passing encoder-specific options. ### Method `to_ini(**kwargs)` ### Parameters #### Query Parameters - **kwargs** - Optional - Encoder specific options (e.g., for `configparser`). ### Response - **string** - The INI formatted string of the dictionary. ### Error Handling - A `ValueError` is raised in case of failure. ``` -------------------------------- ### get_decimal Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value by key or keypath and attempts to return it as a Decimal. If choices are provided and the value is in choices, it returns the value; otherwise, it returns the default. ```APIDOC ## get_decimal ### Description Retrieves a value by key or keypath and attempts to return it as a Decimal. If choices are provided and the value is in choices, it returns the value; otherwise, it returns the default. ### Method `d.get_decimal(key, default=Decimal("0.0"), choices=[])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **Decimal** (Decimal) - The decimal value. #### Response Example None ``` -------------------------------- ### get_float_list Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value by key or keypath and attempts to return it as a list of float values. If a separator is provided and the value is a string, it will be split. ```APIDOC ## get_float_list ### Description Retrieves a value by key or keypath and attempts to return it as a list of float values. If a separator is provided and the value is a string, it will be split. ### Method `d.get_float_list(key, default=[], separator=",")` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **list** (list) - A list of float values. #### Response Example None ``` -------------------------------- ### get_datetime_list Source: https://github.com/fabiocaccamo/python-benedict/blob/main/README.md Retrieves a value by key or keypath and attempts to return it as a list of datetime objects. If a separator is provided and the value is a string, it will be split. ```APIDOC ## get_datetime_list ### Description Retrieves a value by key or keypath and attempts to return it as a list of datetime objects. If a separator is provided and the value is a string, it will be split. ### Method `d.get_datetime_list(key, default=[], format=None, separator=",")` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **list** (list) - A list of datetime objects. #### Response Example None ```