473,584 Members | 2,897 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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('fo o'). 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.
Jun 27 '08 #1
2 1053
On May 9, 10:10*am, dannywebs...@go oglemail.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('fo o'). *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(se q):
"""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
Jun 27 '08 #2
On May 9, 4:09 pm, Paul Hankin <paul.han...@gm ail.comwrote:
On May 9, 10:10 am, dannywebs...@go oglemail.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('fo o'). 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(se q):
"""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.

Jun 27 '08 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
12231
by: Robin Cull | last post by:
Imagine I have a dict looking something like this: myDict = {"key 1": , "key 2": , "key 3": , "key 4": } That is, a set of keys which have a variable length list of associated values after them. What I want to do is filter out a subset of this dict to produce another dict that satisfies a set of criteria (in this case whether it...
35
3721
by: Raymond Hettinger | last post by:
Here is a discussion draft of a potential PEP. The ideas grew out of the discussion on pep-284. Comments are invited. Dart throwing is optional. Raymond Hettinger ------------------------------------------------------------- PEP: 323
59
4279
by: Raymond Hettinger | last post by:
Please comment on the new PEP for reverse iteration methods. Basically, the idea looks like this: for i in xrange(10).iter_backwards(): # 9,8,7,6,5,4,3,2,1,0 <do something with i> The HTML version is much more readable than the ReST version. See: http://www.python.org/peps/pep-0322.html
31
2968
by: Raymond Hettinger | last post by:
Based on your extensive feedback, PEP 322 has been completely revised. The response was strongly positive, but almost everyone preferred having a function instead of multiple object methods. The updated proposal is at: www.python.org/peps/pep-0322.html In a nutshell, it proposes a builtin function that greatly simplifies reverse...
7
1446
by: flacco | last post by:
is there a way to iterate over the *values* in a list/dict/whatever, regardless of whether it's a list, dict, or whatever? ie, the iteration code will not know beforehand what kind of container it's getting.
6
1891
by: tkpmep | last post by:
I have list of lists of the following form L=, , , ] I want to aggregate these lists, i.e. to reduce L to L=, ] #500 = 100+400, 200=300-100 Here's how I have done it: L.sort() for i in range(len(L),0,-1):
3
2046
by: Bengt Richter | last post by:
Has anyone found a way besides not deriving from dict? Shouldn't there be a way? TIA (need this for what I hope is an improvement on the Larosa/Foord OrderedDict ;-) I guess I can just document that you have to spell it dict(d.items()), but I'd like to hide the internal shenanigans ;-) Regards, Bengt Richter
28
7365
by: robert | last post by:
In very rare cases a program crashes (hard to reproduce) : * several threads work on an object tree with dict's etc. in it. Items are added, deleted, iteration over .keys() ... ). The threads are "good" in such terms, that this core data structure is changed only by atomic operations, so that the data structure is always consistent regarding...
18
3710
by: MTD | last post by:
Hello all, I've been messing about for fun creating a trial division factorizing function and I'm naturally interested in optimising it as much as possible. I've been told that iteration in python is generally more time-efficient than recursion. Is that true? Here is my algorithm as it stands. Any suggestions appreciated!
0
7897
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
8190
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7940
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6590
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5705
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5379
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3824
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3850
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2336
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.