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
20 changes: 20 additions & 0 deletions py/dict.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,17 @@ var (
expectingDict = ExceptionNewf(TypeError, "a dict is required")
)

func init() {
StringDictType.Dict["items"] = MustNewMethod("items", func(self Object, args Tuple) (Object, error) {
sMap := self.(StringDict)
o := make([]Object, 0, len(sMap))
for k, v := range sMap {
o = append(o, Tuple{String(k), v})
}
return NewIterator(o), nil
}, 0, "items() -> list of D's (key, value) pairs, as 2-tuples")
}

// String to object dictionary
//
// Used for variables etc where the keys can only be strings
Expand Down Expand Up @@ -100,6 +111,15 @@ func (a StringDict) M__repr__() (Object, error) {
return String(out.String()), nil
}

// Returns a list of keys from the dict
func (d StringDict) M__iter__() (Object, error) {
o := make([]Object, 0, len(d))
for k := range d {
o = append(o, String(k))
}
return NewIterator(o), nil
}

func (d StringDict) M__getitem__(key Object) (Object, error) {
str, ok := key.(String)
if ok {
Expand Down
16 changes: 16 additions & 0 deletions py/tests/dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,20 @@
a = repr({"a":"b","c":5.5})
assert a == "{'a': 'b', 'c': 5.5}" or a == "{'c': 5.5, 'a': 'b'}"

doc="check __iter__"
a = {"a":"b","c":5.5}
l = list(iter(a))
assert "a" in l
assert "c" in l
assert len(l) == 2

doc="check items"
a = {"a":"b","c":5.5}
for k, v in a.items():
assert k in ["a", "c"]
if k == "a":
assert v == "b"
if k == "c":
assert v == 5.5

doc="finished"