Skip to content
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
24 changes: 24 additions & 0 deletions py/dict.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions py/tests/dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down