Skip to content

Iterator for dotty_dict #95

Description

@tpow

I was trying to use dotty like a regular dictionary and it gives an unexpected KeyError exception when trying to iterate over it.

import dotty_dict

d = dotty_dict.dotty(
            {
                "top": {
                    "first": {"a": "alpha", "b": "beta"},
                    "second": {},
                },
                "bottom": {
                },
            }                        
        )
for item in d:
    print(item)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/tpow/example/.venv/lib/python3.11/site-packages/dotty_dict/dotty_dict.py", line 162, in __getitem__
    return get_from(self._split(item), self._data)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/tpow/example/.venv/lib/python3.11/site-packages/dotty_dict/dotty_dict.py", line 154, in get_from
    data = data[it]
           ~~~~^^^^
KeyError: 0

This also throws the same exception when trying to use dotty_dict as a comprehension:

b = [item for item in d if item.startswith("b")]
assert b == ["bottom"]  # <-- never gets here

(This is simply an example. I know there are other convenient ways to retrieve items using dotty_dict.)

Although I could use keys() when iterating, that isn't typically needed for dictionaries and it would be nice if dotty_dict worked the same.

In order to make it behave more like a regular dictionary, I think all dotty_dict needs is a simple __iter__ like this:

    def __iter__(self):                                                        
        for key in self.keys():
            yield key

It may also be that there is something broken in get_from() that I don't quite understand.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions