Skip to content

Commit

Permalink
Added utils.add_key_if_value
Browse files Browse the repository at this point in the history
  • Loading branch information
sgeulette committed Jun 20, 2024
1 parent 22e5276 commit f9e3df7
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
4 changes: 2 additions & 2 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ Changelog
1.0.5 (unreleased)
------------------

- Nothing changed yet.

- Added `utils.add_key_if_value` to add a key in a dic only if value or is not None.
[sgeulette]

1.0.4 (2024-06-11)
------------------
Expand Down
14 changes: 14 additions & 0 deletions imio/pyutils/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from imio.pyutils.system import hashed_filename
from imio.pyutils.system import read_dir_filter
from imio.pyutils.system import read_recursive_dir
from imio.pyutils.utils import add_key_if_value
from imio.pyutils.utils import all_of_dict_values
from imio.pyutils.utils import append
from imio.pyutils.utils import get_clusters
Expand All @@ -31,6 +32,19 @@
class TestUtils(unittest.TestCase):
""" """

def test_add_key_if_value(self):
dic = {}
add_key_if_value(dic, "a", None)
self.assertDictEqual(dic, {})
add_key_if_value(dic, "a", "", strict=True)
self.assertDictEqual(dic, {})
add_key_if_value(dic, "a", "")
self.assertDictEqual(dic, {"a": ""})
add_key_if_value(dic, "b", "b")
self.assertDictEqual(dic, {"a": "", "b": "b"})
add_key_if_value(dic, "c", "c", strict=True)
self.assertDictEqual(dic, {"a": "", "b": "b", "c": "c"})

def test_all_of_dict_values(self):
self.assertListEqual(all_of_dict_values({1: None, 2: "Good", 3: "", 4: "job"}, [1, 2, 3, 4]), ["Good", "job"])
self.assertListEqual(
Expand Down
15 changes: 15 additions & 0 deletions imio/pyutils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,21 @@
import timeit


def add_key_if_value(dic, key, value, strict=False):
"""Add a key to a dict only if a value or is not None.
:param dic: input dictionary
:param key: key to add
:param value: value to add
:param strict: if True, add only if value is considered boolean True
"""
if strict:
if value:
dic[key] = value
elif value is not None:
dic[key] = value


def all_of_dict_values(dic, keys, labels=[], sep=u"="):
"""Returns a not empty values list from a dict following given keys.
Expand Down

0 comments on commit f9e3df7

Please sign in to comment.