This count is going to be high by at least a factor of 2, since you're appending every duplicate key multiple times above. I think that on the whole the script still has the desired effect though :P