python - for loop iterate tuples -
i'm beginner in python (and going coding after 20 years...)
i'm doing small script in order learn irregular english verbs. create dict (it's in french)
verbes = { "abide":["abode","abode","respecter / se conformer à"], "arise":["arisen","arisen","survenir"], }
if want iterate verbes i'm doing exemple:
for verb, (pret, past, trad) in verbes.items(): print "le verbe %s se conjugue au prétérit par %s, au participe passé par %s et se traduit par %s" % (verb, pret, past, trad)
ok works. found out can import random pick 1 random key , value in dictionnary
rand = random.choice(verbes.items())
if print rand have key, value if iterate again have traceback:
traceback (most recent call last): file ".\exverbe1.py", line 209, in <module> verb, (pret, past, trad) in rand.items(): attributeerror: 'tuple' object has no attribute 'items'
i'm not yet @ "tuple" lesson i've tried turn list, dict, etc. without success. looked on "for loop tuple" in stackoverflow without result. i'm asking after 3 hours trying figure out...
random.choice(verbes.items())
picks 1 tuple @ random verbes.items()
. rand
therefore contains 1 item - rand[0]
holds key , rand[1]
value.
if you're trying iterate on items in value list:
for val in rand[1]: print val
to unpack rand
tuple constituents:
verb, (pret, past, trad)
verb
contains key, , pret
, past
, trad
each element in list corresponding key.
Comments
Post a Comment