aioupnp/aioupnp/util.py

50 lines
1.7 KiB
Python
Raw Normal View History

2019-05-21 18:16:30 -04:00
import typing
from collections import OrderedDict
2018-10-07 22:30:13 -04:00
2018-07-26 19:49:33 -04:00
2019-05-21 18:16:30 -04:00
str_any_dict = typing.Dict[str, typing.Any]
2018-07-26 19:49:33 -04:00
2019-05-21 18:16:30 -04:00
def _recursive_flatten(to_flatten: typing.Any, strip: str) -> typing.Any:
if not isinstance(to_flatten, (list, dict)):
return to_flatten
if isinstance(to_flatten, list):
assert isinstance(to_flatten, list)
return [_recursive_flatten(i, strip) for i in to_flatten]
assert isinstance(to_flatten, dict)
keys: typing.List[str] = list(to_flatten.keys())
copy: str_any_dict = OrderedDict()
for k in keys:
item: typing.Any = to_flatten[k]
if strip in k and strip != k:
copy[k.split(strip)[1]] = _recursive_flatten(item, strip)
2018-07-26 19:49:33 -04:00
else:
2019-05-21 18:16:30 -04:00
copy[k] = _recursive_flatten(item, strip)
return copy
2018-07-26 19:49:33 -04:00
2019-05-21 18:16:30 -04:00
def flatten_keys(to_flatten: str_any_dict, strip: str) -> str_any_dict:
keys: typing.List[str] = list(to_flatten.keys())
copy: str_any_dict = OrderedDict()
for k in keys:
item = to_flatten[k]
2018-07-26 19:49:33 -04:00
if strip in k and strip != k:
2019-05-21 18:16:30 -04:00
new_key: str = k.split(strip)[1]
copy[new_key] = _recursive_flatten(item, strip)
2018-07-26 19:49:33 -04:00
else:
2019-05-21 18:16:30 -04:00
copy[k] = _recursive_flatten(item, strip)
return copy
2018-07-26 19:49:33 -04:00
def get_dict_val_case_insensitive(source: typing.Dict[typing.AnyStr, typing.AnyStr],
key: typing.AnyStr) -> typing.Optional[typing.AnyStr]:
2019-05-21 18:16:30 -04:00
match: typing.List[typing.AnyStr] = list(filter(lambda x: x.lower() == key.lower(), source.keys()))
if not len(match):
return None
2018-07-31 16:53:08 -04:00
if len(match) > 1:
raise KeyError("overlapping keys")
2019-05-21 18:16:30 -04:00
if len(match) == 1:
matched_key: typing.AnyStr = match[0]
return source[matched_key]
raise KeyError("overlapping keys")