Go Back   Velocity Reviews > Newsgroups > Python
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

Reply

Python - Grabbing previous iteration in a dict

 
Thread Tools Search this Thread
Old 05-09-2008, 10:10 AM   #1
Default Grabbing previous iteration in a dict


Hello all,

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.

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.

Cheerz

dan.


dannywebster@googlemail.com
  Reply With Quote
Old 05-09-2008, 10:48 AM   #2
Paul Rubin
 
Posts: n/a
Default Re: Grabbing previous iteration in a dict
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.


Paul Rubin
  Reply With Quote
Old 05-09-2008, 03:21 PM   #3
dannywebster@googlemail.com
 
Posts: n/a
Default Re: Grabbing previous iteration in a dict
On May 9, 10:48 am, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> dannywebs...@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?


dannywebster@googlemail.com
  Reply With Quote
Old 05-09-2008, 03:45 PM   #4
Gary Herron
 
Posts: n/a
Default Re: Grabbing previous iteration in a dict
wrote:
> On May 9, 10:48 am, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
>
>> dannywebs...@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



Gary Herron
  Reply With Quote
Old 05-09-2008, 03:55 PM   #5
Hyuga
 
Posts: n/a
Default Re: Grabbing previous iteration in a dict
On May 9, 5:10 am, dannywebs...@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.


Hyuga
  Reply With Quote
Old 05-09-2008, 03:57 PM   #6
Yves Dorfsman
 
Posts: n/a
Default Re: Grabbing previous iteration in a dict
wrote:
>> 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?


Yes, I ran in a situation similar to yours, I read the content of a file,
and had to both keep the order of the lines in the original file, and create
a dictionary from the lines. So I created a class that contained both a
dictionary and a tuple containing the keys of the dictionary in the original
order. Something like this:

class mydict(object):

def __init__(self, filename):
x = [ e.strip().split() for e in file(filename) ]
self.ordered_lines = tuple([ e[0] for e in x ])
self.dictionary = dict( zip(self.ordered_lines, [ e[1:] for e in x]) )

a = mydict('/some/file')
a.ordered_lines
a.dictionary



Yves.
http://www.SollerS.ca


Yves Dorfsman
  Reply With Quote
Old 05-09-2008, 04:09 PM   #7
Paul Hankin
 
Posts: n/a
Default Re: Grabbing previous iteration in a dict
On May 9, 10:10*am, dannywebs...@googlemail.com wrote:
> Hello all,
>
> 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.


Often when you're iterating, 'hacky' code can be lifted out into a
separate generator, keeping the details of the hacks nicely away from
your code. That's true here...

def iterprevious(seq):
"""Generate pairs of (previous element, current element)
from seq."""
last = None
for x in iter(seq):
yield last, x
last = x

Then, when you want use it...

for previous, (key, value) in iterprevious(d.iteritems()):
... In the loop, previous will either be None if we're on the
first element, otherwise (previous_key, previous_value).

--
Paul Hankin


Paul Hankin
  Reply With Quote
Old 05-09-2008, 04:44 PM   #8
dannywebster@googlemail.com
 
Posts: n/a
Default Re: Grabbing previous iteration in a dict
On May 9, 4:09 pm, Paul Hankin <paul.han...@gmail.com> wrote:
> On May 9, 10:10 am, dannywebs...@googlemail.com wrote:
>
> > Hello all,

>
> > 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.

>
> Often when you're iterating, 'hacky' code can be lifted out into a
> separate generator, keeping the details of the hacks nicely away from
> your code. That's true here...
>
> def iterprevious(seq):
> """Generate pairs of (previous element, current element)
> from seq."""
> last = None
> for x in iter(seq):
> yield last, x
> last = x
>
> Then, when you want use it...
>
> for previous, (key, value) in iterprevious(d.iteritems()):
> ... In the loop, previous will either be None if we're on the
> first element, otherwise (previous_key, previous_value).
>
> --
> Paul Hankin



Hi all - some good stuff here. Thanks for the info, I have a few
ideas
to play with.

thanks again

dan.



dannywebster@googlemail.com
  Reply With Quote
Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Sitting 70-536 later this week, advice from previous takers? Tony Wissler MCTS 1 06-12-2007 08:01 AM
Happy Gilmore new LBX DVD vs. previous full screen DVD? Michael DVD Video 12 12-02-2004 12:38 PM
New "Bride of Frankenstein" dvd vs previous dvd? TB DVD Video 7 04-30-2004 11:46 PM
Great Universal Franchise Collections - but too bad for previous buyers djskyler DVD Video 14 01-20-2004 08:08 PM
Alien Quadrilogy vs. previous single DVD editions - any unique material? James DVD Video 6 01-17-2004 05:13 PM




SEO by vBSEO 3.3.2 ©2009, Crawlability, Inc.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46