dictutils.qsdictΒΆ

dictutils.qsdict(qs, *args, strict=False)[source]ΒΆ

Build a nested dict from rows (dicts or objects) by a sequence of selectors.

Parameters:
  • qs (Iterable[Union[Mapping, object]]) – Iterable of mappings or objects to process

  • *args – Selectors - each can be: - Key name (str/int) to access dict keys or object attributes - Callable that takes a row and returns a key - Tuple of selectors for the leaf values (last arg only)

  • strict (bool) – If True, raise KeyError/AttributeError for missing selectors. If False (default), missing selectors yield None keys.

Return type:

dict

Returns:

Nested dict where each level corresponds to a selector

Examples

>>> data = [{"cat": "A", "val": 1}, {"cat": "B", "val": 2}]
>>> qsdict(data, "cat", "val")
{'A': 1, 'B': 2}
>>> qsdict(data, lambda x: x["cat"].lower(), "val")
{'a': 1, 'b': 2}