Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Iterator for dotty_dict #95

Open
tpow opened this issue Mar 23, 2023 · 0 comments
Open

Iterator for dotty_dict #95

tpow opened this issue Mar 23, 2023 · 0 comments

Comments

@tpow
Copy link

tpow commented Mar 23, 2023

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.

Hembury pushed a commit to Hembury/dotty_dict that referenced this issue Jun 5, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant