[Python-3000] Default dict iterator should have been iteritems() (original) (raw)

Noam Raphael noamraph at gmail.com
Thu Sep 6 09:15:31 CEST 2007


(Sorry, it turns out that I posted this reply only to Nick and not to the list, so I post it again.)

On 9/4/07, Nick Coghlan <ncoghlan at gmail.com> wrote:

Containment and iteration really do need to be kept consistent and having the value matter when checking for dictionary containment would be outright bizarre. Put the two together and it makes sense for dictionary iteration and containment tests to both be based on keys. I absolutely agree that containment and iteration should be kept consistent.

I suggest (again, ignoring backwards compatibility completely), that "in" would behave according to the iteration, that is, check if the tuple (key, value) is in dict.items(). If you prefer code:

class DreamDict(dict): def iter(self): return self.iteritems() def contains(self, (key, value)): try: myvalue = self[key] except KeyError: return False return value == myvalue

Indeed, the suggested "in" operator is not very useful, so you'll usually use has_key. But I actually think that "d.has_key(k)" is clearer than "k in d" - There's no "syntactic" reason why "k in d" should mean "k in d.keys()" and not "k in d.values()".*

Noam



More information about the Python-3000 mailing list