Parsing¶
This module contains various useful tools for parsing input data.
- aiuti.parsing.parse_to_dict(items: ~typing.Union[~typing.Mapping[~typing.Any, ~typing.Any], ~typing.Iterable[~typing.Union[~typing.Tuple[~typing.Any, ...], str]]], *, sep: str = '=', parse: ~typing.Callable[[str], ~typing.Any] = <function literal_eval>, parse_keys: bool = True) Dict[Any, Any] ¶
Normalize the given input into a dictionary and parse keys & values as necessary into literal objects.
When given an iterable of strings, they are assumed to be in the form of
<key><sep><value>
likea=b
and will be parsed as such.Keys or values which fail to parse will be retained as is.
By default, both keys and values are parsed literally:
>>> parse_to_dict({'a': '1', '2': '"b"'}) {'a': 1, 2: 'b'}
>>> parse_to_dict(['a=1', '2="b"', '"b"=1.4']) {'a': 1, 2: 'b', 'b': 1.4}
Parsing keys can be disabled with the
parse_keys
parameter:>>> parse_to_dict({'a': '1', '2': '"b"'}, parse_keys=False) {'a': 1, '2': 'b'}
>>> parse_to_dict(['a=1', '2=b'], parse_keys=False) {'a': 1, '2': 'b'}
The default separator can be changed using the
sep
parameter:>>> parse_to_dict(['a:1', '2:"b"', '"b":1.4'], sep=':') {'a': 1, 2: 'b', 'b': 1.4}
- Parameters:
items – Mapping or iterable to parse to a dictionary
sep – For elements that are strings, the separator between the key and value
parse – Function which will be used to try to parse strings into literal values
parse_keys – Try to parse the keys when they are strings?