From 562d3176b5a34b5cdd46ce6e06b6c5d161e33e82 Mon Sep 17 00:00:00 2001 From: Kyle Ellrott Date: Wed, 4 Jan 2023 23:51:20 -0800 Subject: [PATCH 1/2] Adding 'keys' and 'values' methods to dict object --- py/dict.go | 26 ++++++++++++++++++++++++++ py/tests/dict.py | 8 ++++++++ 2 files changed, 34 insertions(+) diff --git a/py/dict.go b/py/dict.go index 1710b7da..10c2d33f 100644 --- a/py/dict.go +++ b/py/dict.go @@ -41,6 +41,32 @@ func init() { return NewIterator(o), nil }, 0, "items() -> list of D's (key, value) pairs, as 2-tuples") + StringDictType.Dict["keys"] = MustNewMethod("keys", func(self Object, args Tuple) (Object, error) { + err := UnpackTuple(args, nil, "keys", 0, 0) + if err != nil { + return nil, err + } + sMap := self.(StringDict) + o := make([]Object, 0, len(sMap)) + for k := range sMap { + o = append(o, String(k)) + } + return NewIterator(o), nil + }, 0, "keys() -> list of D's keys, as a list") + + StringDictType.Dict["values"] = MustNewMethod("values", func(self Object, args Tuple) (Object, error) { + err := UnpackTuple(args, nil, "values", 0, 0) + if err != nil { + return nil, err + } + sMap := self.(StringDict) + o := make([]Object, 0, len(sMap)) + for _, v := range sMap { + o = append(o, v) + } + return NewIterator(o), nil + }, 0, "values() -> list of D's values, as a list") + StringDictType.Dict["get"] = MustNewMethod("get", func(self Object, args Tuple) (Object, error) { var length = len(args) switch { diff --git a/py/tests/dict.py b/py/tests/dict.py index cb14dbc2..afc4e509 100644 --- a/py/tests/dict.py +++ b/py/tests/dict.py @@ -28,6 +28,14 @@ assert a.get('b',1) == 1 assert a.get('b',True) == True +doc="check keys" +a = {"a":1} +assert a.keys() == ["a"] + +doc="check values" +a = {"a":1} +assert a.values() == [1] + doc="check items" a = {"a":"b","c":5.5} for k, v in a.items(): From d6fdd0152b30db364c9377119b78fc08cc323c28 Mon Sep 17 00:00:00 2001 From: Kyle Ellrott Date: Wed, 4 Jan 2023 23:56:01 -0800 Subject: [PATCH 2/2] Fixing unit test --- py/tests/dict.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/py/tests/dict.py b/py/tests/dict.py index afc4e509..d6140e47 100644 --- a/py/tests/dict.py +++ b/py/tests/dict.py @@ -30,11 +30,11 @@ doc="check keys" a = {"a":1} -assert a.keys() == ["a"] +assert list(a.keys()) == ["a"] doc="check values" a = {"a":1} -assert a.values() == [1] +assert list(a.values()) == [1] doc="check items" a = {"a":"b","c":5.5}