diff --git a/aiida/orm/nodes/data/dict.py b/aiida/orm/nodes/data/dict.py index e0a975f916..833c3ca4a0 100644 --- a/aiida/orm/nodes/data/dict.py +++ b/aiida/orm/nodes/data/dict.py @@ -8,7 +8,10 @@ # For further information please visit http://www.aiida.net # ########################################################################### """`Data` sub class to represent a dictionary.""" +from __future__ import annotations + import copy +import typing as t from aiida.common import exceptions @@ -79,6 +82,15 @@ def __contains__(self, key: str) -> bool: """Return whether the node contains a key.""" return key in self.base.attributes + def get(self, key: str, default: t.Any | None = None, /): # type: ignore[override] # pylint: disable=arguments-differ + """Return the value for key if key is in the dictionary, else default. + + :param key: The key whose value to return. + :param default: Optional default to return in case the key does not exist. + :returns: The value if the key exists, otherwise the ``default``. + """ + return self.base.attributes.get(key, default) + def set_dict(self, dictionary): """Replace the current dictionary with another one. diff --git a/tests/orm/nodes/data/test_dict.py b/tests/orm/nodes/data/test_dict.py index b8ffc9f01f..f49e98b869 100644 --- a/tests/orm/nodes/data/test_dict.py +++ b/tests/orm/nodes/data/test_dict.py @@ -44,6 +44,15 @@ def test_dict_property(dictionary): assert node.dict.nested == dictionary['nested'] +def test_get(dictionary): + """Test the ``get`` method.""" + node = Dict(dictionary) + assert node.get('invalid') is None + assert node.get('invalid', 'default') == 'default' + assert node.get('value') == dictionary['value'] + assert node.get('nested') == dictionary['nested'] + + def test_get_item(dictionary): """Test the ``__getitem__`` method.""" node = Dict(dictionary)