def test_is_dict_returns_false_for_arguments_other_than_a_dict(): """ Test is_dict() for valid arguments of other than dict data type. """ assert is_dict("") is False assert is_dict("Test") is False assert is_dict(u"Hello") is False assert is_dict(None) is False assert is_dict([]) is False
def merge(dict1, dict2): """ Merge two dictionaries recursively and return the merged dict. (Immutable) """ result = deepcopy(dict1) for key, value in dict2.items(): if is_dict(value): result[key] = merge(result.get(key, {}), value) else: result[key] = deepcopy(dict2[key]) return result
def dict_to_list(dict: Dict, name_key: str = "name", value_key: str = "value"): """ Returns a list of dictionaries with `name` and `value` keys for all key-value pair in given dictionary. """ if not is_dict(dict): raise AttributeError( "Argument must be a dictionary, invalid argument received '{}'.". format(dict)) list = [] for key, val in dict.items(): list.append({name_key: key, value_key: val}) return list
def without_attr(src, attrs, deep=True): """ Return a new copy of source dictionary removing the attributes provided. """ result = {} for key, value in src.items(): if deep and is_dict(value): value = without_attr(value, attrs, deep) elif deep and is_iterable(value) and not is_string(value): value = list(map(lambda x: without_attr(x, attrs, deep), value)) if key not in attrs: result[key] = value return result
def map_dict(dict, callback, recursive=False): """ Returns a new dictionary after applying a callback function over each item in given dictionary. :param dict Dictionary of items to iterate the callback functions over. :type dict :param callback Function that is called with each value passed as an argument. :type function :param recursive Boolean value that determines whether or not to apply callback function recursively. :type bool """ new_dict = {} for key, value in dict.items(): if recursive and is_dict(value): new_dict[key] = map_dict(value, callback, recursive=recursive) else: new_dict[key] = callback(key, value) return new_dict
def with_only(src, attrs): """ Return a new copy of source dictionary containing only the attributes provided. """ if not is_dict(src): raise AttributeError( "First argument must be a dictionary, invalid argument received '{}'." .format(src)) elif not is_list(attrs): raise AttributeError( "Second argument must be a list, invalid argument received '{}'.". format(attrs)) result = {} for key, value in src.items(): if key in attrs: result[key] = value return result
def test_is_dict_returns_true_for_a_valid_arguments_of_dict_data_type(): """ Test is_dict() for valid arguments of dict data type. """ assert is_dict({}) is True assert is_dict({"foo": "bar"}) is True assert is_dict(dict()) is True