Grabbing previous iteration in a dict
Hyuga
hyugaricdeau at gmail.com
Fri May 9 10:55:10 EDT 2008
On May 9, 5:10 am, dannywebs... at googlemail.com wrote:
> I have a dictionary of which i'm itervalues'ing through, and i'll be
> performing some logic on a particular iteration when a condition is
> met with trusty .startswith('foo'). I need to grab the previous
> iteration if this condition is met. I can do something with an extra
> var to hold every iteration while iterating, but this is hacky and not
> elegant.
Why is that so terrible?
previous = None
for key in mydict:
if key.starswith('foo') and previous is not None:
# ...do stuff...
previous = key
Doesn't seem too ugly to me.
> Is there a mechanism whereby I can just index the dict value
> subscripts like in an array? I could just rewind by 1 if so.
You can't rely on the keys in a dictionary being in any specific
order. But if you want a list of the keys you can just call
mydict.keys() which will give a copy of the dictionary's keys in a
list. Then you can iterate that and use it however you would use any
other list. Note that it's a copy though. It might help if you
better explained exactly what you need to do.
More information about the Python-list
mailing list