Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding 'keys' and 'values' methods to dict object #213

Merged
merged 2 commits into from
Jan 9, 2023
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
26 changes: 26 additions & 0 deletions py/dict.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
8 changes: 8 additions & 0 deletions py/tests/dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,14 @@
assert a.get('b',1) == 1
assert a.get('b',True) == True

doc="check keys"
a = {"a":1}
assert list(a.keys()) == ["a"]

doc="check values"
a = {"a":1}
assert list(a.values()) == [1]

doc="check items"
a = {"a":"b","c":5.5}
for k, v in a.items():
Expand Down