Skip to content

Commit f3df7a4

Browse files
Sungmin-Joocorona10
authored andcommitted
(RE)Implementing a "get" function on a "Dictionary" (#106)
Implement the "get" function and add unit test. fixes #105
1 parent 720c16a commit f3df7a4

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

py/dict.go

+24
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,30 @@ func init() {
3636
}
3737
return NewIterator(o), nil
3838
}, 0, "items() -> list of D's (key, value) pairs, as 2-tuples")
39+
40+
StringDictType.Dict["get"] = MustNewMethod("get", func(self Object, args Tuple) (Object, error) {
41+
var length = len(args)
42+
switch {
43+
case length == 0:
44+
return nil, ExceptionNewf(TypeError, "%s expected at least 1 arguments, got %d", "items()", length)
45+
case length > 2:
46+
return nil, ExceptionNewf(TypeError, "%s expected at most 2 arguments, got %d", "items()", length)
47+
}
48+
sMap := self.(StringDict)
49+
if str, ok := args[0].(String); ok {
50+
if res, ok := sMap[string(str)]; ok {
51+
return res, nil
52+
}
53+
54+
switch length {
55+
case 2:
56+
return args[1], nil
57+
default:
58+
return None, nil
59+
}
60+
}
61+
return nil, ExceptionNewf(KeyError, "%v", args[0])
62+
}, 0, "gets(key, default) -> If there is a val corresponding to key, return val, otherwise default")
3963
}
4064

4165
// String to object dictionary

py/tests/dict.py

+8
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,14 @@
1919
assert "c" in l
2020
assert len(l) == 2
2121

22+
doc="check get"
23+
a = {"a":1}
24+
assert a.get('a') == 1
25+
assert a.get('a',100) == 1
26+
assert a.get('b') == None
27+
assert a.get('b',1) == 1
28+
assert a.get('b',True) == True
29+
2230
doc="check items"
2331
a = {"a":"b","c":5.5}
2432
for k, v in a.items():

0 commit comments

Comments
 (0)