Python For Loop Examples

List

l = [ 'd','c','b','a' ]

# ---- print in list order

for v in l:
    print(v)

# ---- print enumerated values (index/value)

for i,v in enumerate(l):
    print(i,v)

# print ---- print sorted by value
print()
for v in sorted(l):
    print(v)

Dictionary

d = { 'z3':'jkl', 'z2':'def', 'z1':'ghi', 'z4':'abc' }

# ---- print dictionary key (no order)

for k in d:
    print(k)

# ---- print dictionary key and value (no order)

for k in d:
    print(k,d[k])

# ---- print key and value sort by key

for k in sorted(d):
    print(k,d[k])

# ---- print dictionary tuple (key/value) sort by key

for i in sorted(d.items()):
    print(i)

# ---- print key and value sorted by key

for k,v in sorted(d.items()):
    print(k,v)

# ---- print key and value sorted by value in reverse order

for i in sorted(d.items(), key = lambda x : x[1], reverse = True):
    print(i[0],i[1])

# ---- print a list of tuple values sorted by a tuple column

tlst = [ ('a3','b3',  20),
         ('a2','b2', 100),
         ('a1','b1',  10),
         ('a0','b0',  30) ]

# ---- print raw tuples

for x in tlst:
    print(x)

# ---- print tuple vales sorted on tuple x[2] (third column)

for x in sorted(tlst, key = lambda x : x[2], reverse = True):
    print (x[0],x[1],x[2])