diff --git a/tests/test_udict.py b/tests/test_udict.py index f656c1e..d4c3b9f 100644 --- a/tests/test_udict.py +++ b/tests/test_udict.py @@ -74,6 +74,20 @@ def test_set_item(self): d[:] = [1, 2] self.assertDictEqual(d.dictionary, {'hello': 1, 'hi': 2}) + def test_get(self): + d = UDict({2: 1, 4: 91, 1: 12}) + self.assertEqual(d.get(index=1), d.get(key=2)) + self.assertEqual(d.get(index=2), d.get(key=4)) + self.assertEqual(d.get(index=3), d.get(key=1)) + + # TODO: test_del_item + # TODO: test_len_and_iter + # TODO: test_bool + # TODO: test_contains + # TODO: test_str_and_repr + # TODO: test_cmp_and_eq + # TODO: test_math_operations + if __name__ == '__main__': unittest.main() diff --git a/ufpy/udict.py b/ufpy/udict.py index 1762a02..a2f6e94 100644 --- a/ufpy/udict.py +++ b/ufpy/udict.py @@ -137,6 +137,23 @@ def __delitem__(self, key: KT | int | slice) -> None: self.__dict = del_items_for_several_keys(self.__dict, keys) + # get + def get(self, *, key: KT | None = None, index: int | None = None) -> VT | DV: + """ + Get a value with key or it's index. + + :param key: Key of value in dict (optional) + :param index: Index of value in dict (optional) + :return: Value or default value + + :exception ValueError: You defined both key and index params + """ + if key and index: + raise ValueError('You defined both key and index params. Please cancel the definition one of this params.') + if index and index > len(self): + raise IndexError('Index is bigger that length of UDict.') + return self[self.keys[index-1]] if index else self[key] + # Len, iterator and reversed version def __len__(self) -> int: return len(self.items)