Grabbing previous iteration in a dict
Gary Herron
gherron at islandtraining.com
Fri May 9 10:45:33 EDT 2008
dannywebster at googlemail.com wrote:
> On May 9, 10:48 am, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
>
>> dannywebs... at googlemail.com writes:
>>
>>> 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.
>>>
>> You cannot rely on the elements of a dictionary being in any
>> particular order (dicts are internally hash tables), so the above
>> is almost certainly ont what you want.
>>
>
>
> Hi - thanks for your reply. How about if I made the dict into a list
> (of
> which I have done). How would I then reference the previous item?
> Can they
> be indexed?
> --
> http://mail.python.org/mailman/listinfo/python-list
>
Yes:
listOfItems = DICT.items()
for i in range(len(listOfItems)):
k,v = listOfItems[i] # Current key,value pair
if whatever:
kPrev,vPrev = listOfItems[i-1] # Previous key,value pair
Still, since there is no proscribed order in which the items are placed
into the list, I wonder how this can be useful. However, this *does*
do what you asked.
Gary Herron
More information about the Python-list
mailing list