Skip to content

Commit

Permalink
Dict: implement items() method
Browse files Browse the repository at this point in the history
This allows the user to directly iterate over the `Dict` items instead
of first retrieving the `dict` with `get_dict()` method:

```python
In [1]: d = Dict({'a': 1, 'b': {'c': 2}})

In [2]: for k, v in d.items():
   ...:     print(k, v)
   ...:
a 1
b {'c': 2}
```
  • Loading branch information
mbercx committed Jan 26, 2022
1 parent af3bb3d commit b6f647a
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
5 changes: 5 additions & 0 deletions aiida/orm/nodes/data/dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,11 @@ def keys(self):
for key in self.attributes.keys():
yield key

def items(self):
"""Iterator of all items stored in the Dict node."""
for key, value in self.attributes_items():
yield key, value

@property
def dict(self):
"""Return an instance of `AttributeManager` that transforms the dictionary into an attribute dict.
Expand Down
7 changes: 7 additions & 0 deletions tests/orm/nodes/data/test_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ def test_keys(dictionary):
assert sorted(node.keys()) == sorted(dictionary.keys())


@pytest.mark.usefixtures('clear_database_before_test')
def test_items(dictionary):
"""Test the ``items`` method."""
node = Dict(dictionary)
assert sorted(node.items()) == sorted(dictionary.items())


@pytest.mark.usefixtures('clear_database_before_test')
def test_get_dict(dictionary):
"""Test the ``get_dict`` method."""
Expand Down

0 comments on commit b6f647a

Please sign in to comment.