Hello guys! I have a Table, wanna exclude items according to some condition. In python I would create an entire new dictionary, like this:
What's the best way to do this in nim? I currently use this piece of code, but I'm not sure whether it is safe to delete items while iterating over:
for key, value in old_dict.pairs():
if value != something:
old_dict.del(key) # <-- this smells bad
Thanks @Tiberium
Not great options though :(
I don't want to make any guarantees, but the iterator doesn't look very magical:
iterator pairs*[A, B](t: Table[A, B]): (A, B) =
## iterates over any (key, value) pair in the table `t`.
for h in 0..high(t.data):
if isFilled(t.data[h].hcode): yield (t.data[h].key, t.data[h].val)
Nope, it's just like del.
pairs implementation looks safe enough, I will check that
I don't want to make any guarantees, but the iterator doesn't look very magical:
But you also need to check del's implementation. ;-) Which looks safe too though it's an implementation detail, better use a two step process as the others suggested.
Yeah..While right now del does not shrink the table, it could in the future.
Another reason to create a new table, @c0ntribut0r is that if you delete "most" of the entries then iteration will become slow (skipping many unoccupied slots), though of course you may not iterate over it afterwards (or delete many entries). Indeed, such slow iteration is one reason why auto-compaction upon del might happen someday.
Python dicts raise an exception if you try to insert or delete while iterating over one. It might be safer for Nim Tables to also raise in such circumstances, perhaps only in non-release mode. It's probably no more than the iterator setting a flag in the Table object.