I am newbie in Python.
Dictionary has multiple values.
dc = {1:['2', '3'], 2:['3'], 3:['3', '4']}
If you iterate over 'dc' you find there are three occurrences of '3'. First occurrence is in 1:['2','3']. I would like to iterate over dict so that
if first occurrence of '3' occurs:
dosomething()
else occurrence of '3' afterwards:#i.e. 2nd time, 3rd time....
dosomethingelse()
How can I do this in Python
Thank you.
Assuming the values in the dict are the lists:
foundThree = False
for key, val in dc.items():
if '3' in val and not foundThree:
foundThree = True
# doSomething()
elif '3' in val:
# doSomethingElse()
else:
# doAnotherThing()
Edit (update for your comments about finding the first '3' in the list which is the value of a dict item) - this should work:
for key, val in dc.items():
foundThree = False
for n in val:
if n == '3' and not foundThree:
foundThree = True
# doSomething()
elif n == '3':
# doSomethingElse()
else:
# doAnotherThing()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With