Reputation: 181
I have nested for loops, i think this is making things complicated here. Here is the dict i have
dict1 = {'1': '##', '2': '##'}
I am looping through this dict and here is the code
for key,value in dict1.items():
###some code ###
if ##condition is true move to next key in the for loop which is '2'##
dict1.next()
I have used dict1.next(). But this is throwing an error "dict' object has no attribute 'next'"
Even tried dict1[key] += 1 and dict1[key] = dict1.setdefault(key, 0) + 1
I understand when skipping to next key in dictionary we have to refer index of key to move on to next item. But no luck with anything and I m not sure using "continue" would fulfil my purpose, because currently I have only one value for each corresponding key ("continue" works if it so), but I want to use this code even if each key had more than one value respectively. Such that "If" condition is true for key 1 and its first corresponding value, the next iteration should be for key 2 and its values respectively.
Sorry for long story
Upvotes: 1
Views: 13332
Reputation: 10631
what's wrong with using continue?
dict1 = {'1': [1,4,7], '2': '##'}
for key in dict1.keys():
if key == "1":
continue
else:
print key, dict1[key]
>>> '2 ##'
You can have the nexy key with the following:
keys = dict1.keys()
n = len(keys)
for i in range(n):
thisKey = keys[i]
if some_condition():
nextKey = keys[(i + 1) % n]
nextValue = dict1[nextKey]
print thisKey, nextValue
You have a list of keys, you iterate over the length of the keys. If your condition is true, you can extract the next key and value.
Upvotes: 3