Riken Shah
Riken Shah

Reputation: 3154

incrementing key,value pair inside for loop iterating over dictionary

How can I increment key value pair inside a for loop while iterating over dictionary in python?

for key,value in mydict.iteritems(): 
    if condition:
        #inc key,value
    #something to do

I have tried using next(mydict.iteritems()) and mydict.iteritems().next() but in vain.

I am using python2.7.

EDIT - I know that forloop automatically increments the key,value pair. I want to manually increment to next pair ( Thus resulting in 2 increments). Also I can't use continue because I want both the key value pair to be accessible at same time. So that when I increment, I have the current key value pair as well as the next. If I use continue, I lose access to current and only get next key,value pair.

Upvotes: 1

Views: 2050

Answers (3)

miles82
miles82

Reputation: 6794

If you need simultaneous access to two key-value pairs use pairwise from itertools recipes.

from itertools import izip, tee

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

Upvotes: 1

martineau
martineau

Reputation: 123483

Do you mean something like this?

mydict = {'a': 1, 'b': 2, 'c': 3}

items = mydict.iteritems()
for key,value in items:
    if key == 'b':  # some condition
        try:
            key,value = next(items)
        except StopIteration:
            break
    print(key, value)

Output:

('a', 1)
('c', 3)

Upvotes: 2

Ihor Pomaranskyy
Ihor Pomaranskyy

Reputation: 5621

You don't have to touch key and value:

skip = False
for key, value in mydict.iteritems(): 
    skip = not skip
    if skip:
        continue
    # something to do

If you need to have key/value from previous step, just store it:

skip = False
prev_item = None
for key, value in mydict.iteritems(): 
    skip = not skip
    if skip:
        prev_item = key, value
        continue
    # something to do. can access prev_item.

Upvotes: 0

Related Questions