Skip to content

498 Add list to dict utility to parse variables #904

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

Merged
merged 7 commits into from
Aug 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions monai/utils/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
import collections.abc
import itertools
import random
from ast import literal_eval
from distutils.util import strtobool
from typing import Any, Callable, Optional, Sequence, Tuple, Union

import numpy as np
Expand Down Expand Up @@ -217,3 +219,37 @@ def set_determinism(
torch.backends.cudnn.benchmark = False
else:
torch.backends.cudnn.deterministic = False


def list_to_dict(items):
"""
To convert a list of "key=value" pairs into a dictionary.
For examples: items: `["a=1", "b=2", "c=3"]`, return: {"a": "1", "b": "2", "c": "3"}.
If no "=" in the pair, use None as the value, for example: ["a"], return: {"a": None}.
Note that it will remove the blanks around keys and values.

"""

def _parse_var(s):
items = s.split("=", maxsplit=1)
key = items[0].strip(" \n\r\t'")
value = None
if len(items) > 1:
value = items[1].strip(" \n\r\t'")
return key, value

d = dict()
if items:
for item in items:
key, value = _parse_var(item)

try:
if key in d:
raise KeyError(f"encounter duplicated key {key}.")
d[key] = literal_eval(value)
except ValueError:
try:
d[key] = bool(strtobool(str(value)))
except ValueError:
d[key] = value
return d
52 changes: 52 additions & 0 deletions tests/test_list_to_dict.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Copyright 2020 MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import unittest

from parameterized import parameterized

from monai.utils import list_to_dict

TEST_CASE_1 = [
["a=1", "b=2", "c=3", "d=4"],
{"a": 1, "b": 2, "c": 3, "d": 4},
]

TEST_CASE_2 = [
["a=a", "b=b", "c=c", "d=d"],
{"a": "a", "b": "b", "c": "c", "d": "d"},
]

TEST_CASE_3 = [
["a=0.1", "b=0.2", "c=0.3", "d=0.4"],
{"a": 0.1, "b": 0.2, "c": 0.3, "d": 0.4},
]

TEST_CASE_4 = [
["a=True", "b=TRUE", "c=false", "d=FALSE"],
{"a": True, "b": True, "c": False, "d": False},
]

TEST_CASE_5 = [
["a='1'", "b=2 ", " c = 3", "d='test'", "'e'=0", "f", "g=None"],
{"a": 1, "b": 2, "c": 3, "d": "test", "e": 0, "f": None, "g": None},
]


class TestListToDict(unittest.TestCase):
@parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4, TEST_CASE_5])
def test_value_shape(self, input, output):
result = list_to_dict(input)
self.assertDictEqual(result, output)


if __name__ == "__main__":
unittest.main()