Is this both legal and safe?: foreach(key; assocArray) if(key != "foobar") assocArray.remove("foobar"); If not, then what about this?: foreach(key; assocArray.byKey()) if(key != "foobar") assocArray.remove("foobar");