diff --git a/py/dict.go b/py/dict.go index 94974a00..61b6e5cd 100644 --- a/py/dict.go +++ b/py/dict.go @@ -36,6 +36,30 @@ func init() { } return NewIterator(o), nil }, 0, "items() -> list of D's (key, value) pairs, as 2-tuples") + + StringDictType.Dict["get"] = MustNewMethod("get", func(self Object, args Tuple) (Object, error) { + var length = len(args) + switch { + case length == 0: + return nil, ExceptionNewf(TypeError, "%s expected at least 1 arguments, got %d", "items()", length) + case length > 2: + return nil, ExceptionNewf(TypeError, "%s expected at most 2 arguments, got %d", "items()", length) + } + sMap := self.(StringDict) + if str, ok := args[0].(String); ok { + if res, ok := sMap[string(str)]; ok { + return res, nil + } + + switch length { + case 2: + return args[1], nil + default: + return None, nil + } + } + return nil, ExceptionNewf(KeyError, "%v", args[0]) + }, 0, "gets(key, default) -> If there is a val corresponding to key, return val, otherwise default") } // String to object dictionary diff --git a/py/tests/dict.py b/py/tests/dict.py index 418792a4..1fa317c3 100644 --- a/py/tests/dict.py +++ b/py/tests/dict.py @@ -19,6 +19,14 @@ assert "c" in l assert len(l) == 2 +doc="check get" +a = {"a":1} +assert a.get('a') == 1 +assert a.get('a',100) == 1 +assert a.get('b') == None +assert a.get('b',1) == 1 +assert a.get('b',True) == True + doc="check items" a = {"a":"b","c":5.5} for k, v in a.items():