AttrsDictΒΆ

class dbetto.attrsdict.AttrsDict(value=None, readonly=False)

Access dictionary items as attributes.

Examples

>>> d = AttrsDict({"key1": {"key2": 1}})
>>> d.key1.key2
1
>>> d1 = AttrsDict()
>>> d1["a"] = 1
>>> d1.a
1
Parameters:
group(label)

Group dictionary according to a label.

This is equivalent to map() with unique set to False.

Parameters:

label (str) – name (key) at which the new label can be found. If nested in dictionaries, use . to separate levels, e.g. level1.level2.label.

Return type:

AttrsDict

Examples

>>> d = AttrsDict({
...   "a": {
...     "type": "A",
...     "data": 1
...   },
...   "b": {
...     "type": "A",
...     "data": 2
...   },
...   "c": {
...     "type": "B",
...     "data": 3
...   },
... })
>>> d.group("type").keys()
dict_keys(['A', 'B'])
>>> d.group("type").A.values()
dict_values([{'type': 'A', 'data': 1}, {'type': 'A', 'data': 2}])
>>> d.group("type").B.values()
dict_values([{'type': 'B', 'data': 3}])
>>> d.group("type").A.map("data")[1]
{'type': 'A', 'data': 1}

See also

map

map(label, unique=True)

Remap dictionary according to an alternative unique label.

Loop over keys in the first level and search for key named label in their values. If label is found and its value newid is unique, create a mapping between newid and the first-level dictionary obj. If label is of the form key.label, label will be searched in a dictionary keyed by key. If the label is unique a dictionary of dictionaries will be returned, if not unique and unique is false, a dictionary will be returned where each entry is a dictionary of dictionaries keyed by an arbitrary integer.

Parameters:
  • label (str) – game (key) at which the new label can be found. If nested in dictionaries, use . to separate levels, e.g. level1.level2.label.

  • unique (bool) – bool specifying whether only unique keys are allowed. If true will raise an error if the specified key is not unique.

Return type:

AttrsDict

Examples

>>> d = AttrsDict({
...   "a": {
...     "id": 1,
...     "group": {
...       "id": 3,
...     },
...     "data": "x"
...   },
...   "b": {
...     "id": 2,
...     "group": {
...       "id": 4,
...     },
...     "data": "y"
...   },
... })
>>> d.map("id")[1].data == "x"
True
>>> d.map("group.id")[4].data == "y"
True

Note

No copy is performed, the returned dictionary is made of references to the original objects.

Warning

The result is cached internally for fast access after the first call. If the dictionary is modified, the cache gets cleared.

reset()

Reset this instance by removing all cached data.

Return type:

None

to_dict()

Return a plain dict representation of the object.

Nested AttrsDict instances and lists are recursively converted to built-in containers to ensure the result is fully serialisable by callers expecting standard dictionaries.

Return type:

dict