python - OrderedDictionary.popitem() unable to iterate over all values? -
i try iterate on ordered dictionary in last in first out order. while standard dictionary works fine, first solution ordereddict reacts strange. seems, while popitem()
returns 1 key/value pair (but somehow sequentially, since can't replace kv_pair
2 variables), iteration finished then. see no easy way proceed next key/value pair.
while found 2 working alternatives (shown below), both of them lack elegance of normal dictionary approach.
from found in online help, impossible decide, assume have wrong expectations. there more elgant approach?
from collections import ordereddict normaldict = {"0": "a0.csf", "1":"b1.csf", "2":"c2.csf"} k, v in normaldict.iteritems(): print k,":",v d = ordereddict() d["0"] = "a0.csf" d["1"] = "b1.csf" d["2"] = "c2.csf" print d, "****" kv_pair in d.popitem(): print kv_pair print "++++" k in reversed(d.keys()): print k, d[k] print "%%%%" while len(d) > 0: k, v = d.popitem() print k, v
dict.popitem()
not same thing dict.iteritems()
; removes one pair dictionary tuple, , looping on pair.
the efficient method use while
loop instead; no need call len()
, test against dictionary itself, empty dictionary considered false:
while d: key, value = d.popitem() print key, value
the alternative use reversed()
:
for key, item in reversed(d.items()): print key, value
but requires whole dictionary copied list first.
however, if looking fifo queue, use collections.deque()
instead:
from collections import deque d = deque(["a0.csf", "b1.csf", "c2.csf"]) while d: item = d.pop()
or use deque.reverse()
.
Comments
Post a Comment