8000 Add key value pairs to dict utility fn by RobertLucian · Pull Request #11748 · localstack/localstack · GitHub
[go: up one dir, main page]

Skip to content

Add key value pairs to dict utility fn #11748

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
Nov 1, 2024
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
16 changes: 16 additions & 0 deletions localstack-core/localstack/utils/strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,3 +203,19 @@ def prepend_with_slash(input: str) -> str:
if not input.startswith("/"):
return f"/{input}"
return input


def key_value_pairs_to_dict(pairs: str, delimiter: str = ",", separator: str = "=") -> dict:
"""
Converts a string of key-value pairs to a dictionary.

Args:
pairs (str): A string containing key-value pairs separated by a delimiter.
delimiter (str): The delimiter used to separate key-value pairs (default is comma ',').
separator (str): The separator between keys and values (default is '=').

Returns:
dict: A dictionary containing the parsed key-value pairs.
"""
splits = [split_pair.partition(separator) for split_pair in pairs.split(delimiter)]
return {key.strip(): value.strip() for key, _, value in splits}
19 changes: 18 additions & 1 deletion tests/unit/utils/test_strings.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,24 @@
from localstack.utils.strings import prepend_with_slash
from localstack.utils.strings import (
key_value_pairs_to_dict,
prepend_with_slash,
)


def test_prepend_with_slash():
assert prepend_with_slash("hello") == "/hello"
assert prepend_with_slash("/world") == "/world"
assert prepend_with_slash("//world") == "//world"


def test_key_value_pairs_to_dict():
assert key_value_pairs_to_dict("a=1,b=2,c=3") == {"a": "1", "b": "2", "c": "3"}
assert key_value_pairs_to_dict("a=1;b=2;c=3", delimiter=";", separator="=") == {
"a": "1",
"b": "2",
"c": "3",
}
assert key_value_pairs_to_dict("a=1;b=2;c=3", delimiter=";", separator=":") == {
"a=1": "",
"b=2": "",
"c=3": "",
}
Loading
0