From b6f647abe4094a5e06bb6025ac896f77139d7241 Mon Sep 17 00:00:00 2001 From: Marnik Bercx Date: Wed, 26 Jan 2022 10:00:13 +0100 Subject: [PATCH] `Dict`: implement `items()` method 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} ``` --- aiida/orm/nodes/data/dict.py | 5 +++++ tests/orm/nodes/data/test_dict.py | 7 +++++++ 2 files changed, 12 insertions(+) diff --git a/aiida/orm/nodes/data/dict.py b/aiida/orm/nodes/data/dict.py index fd59017de4..03d3eb9d10 100644 --- a/aiida/orm/nodes/data/dict.py +++ b/aiida/orm/nodes/data/dict.py @@ -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. diff --git a/tests/orm/nodes/data/test_dict.py b/tests/orm/nodes/data/test_dict.py index 1b475ed9ff..350492c97f 100644 --- a/tests/orm/nodes/data/test_dict.py +++ b/tests/orm/nodes/data/test_dict.py @@ -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."""