[Python-Dev] non-mutating 'choose' to go with 'dict.popitem'? (original) (raw)

Tim Peters tim.one@home.com
Wed, 9 May 2001 02:48:12 -0400


[Tim]

Given the new dict iterators in 2.2, there's an easier fast way that doesn't mutate the dict even under the covers:

def arb(dict): if dict: return dict.iteritems().next() raise KeyError("arb passed an empty dict")

[Thomas Wouters]

You probably want:

arb = dict.iteritems().next so that you don't keep on returning the same key,value pair.

No, I would not want that. If "arbitrary" suffices, then by defn. any element is "good enough". If it's not good enough to get the same one back every time, then I want a stronger guarantee about what arb() returns than the inexplicable behavior of repeated calls to dict.iteritems().next in the presence of dict mutation. But as I've said several times before , I'm still asking for an algorithm where arb() is actually useful (as opposed to .popitem(), which is dead easy to explain in the presence of mutation; your version of arb() can, e.g., return a given entry more than once, may skip entries, and may raise StopIteration with unexamined entries remaining in the dict).

not-inclined-to-accept-shallow-comfort-at-the-cost-of-deep-confusion-ly y'rs - tim