#!/usr/bin/python3
#-------------------------------------------------------------------------------
# Sort an address book
#-------------------------------------------------------------------------------
print("Content-Type: text/html \n")

addrbook = [ {'role1':('Alan','lname1','mid1','email1')}, 
             {'Role2':('jim', 'Lname2', '',   'Email2')} ]

role  = 'instructor'
fname = 'Sam'
lname = 'Sultan'
mid   = 'E'
email = 'x@x.com'

info  = (fname, lname, mid, email)
entry = {role : info}

addrbook.append(entry)                          # add another entry to addrbook

#=====================================================
def display(addrbook): 
    for entry in addrbook:
        for (role,info) in entry.items():
            print(role + '=>' + str(info) + '<br>')
    print('<br>')

def by_fname(element):
    [(k,v)] = element.items()           #unpack the element.items()
    return v[0]                         #which is a list of tuple

def by_lname(element):
    [(k,v)] = element.items()           
    return v[1].lower()                 
#=====================================================

print("Original Address Book...<br>")
display(addrbook)

print("Sorted by fname...<br>")
addrbook2 = sorted(addrbook, key=by_fname)
display(addrbook2)

print("Sorted by lname descending & case insensitive...<br>")
addrbook3 = sorted(addrbook, key=by_lname, reverse=True)
display(addrbook3)



#=== link to see the python code =================================================
import os, sys
sys.path.insert(0,'/home/s/sultans/web/python/demo')
import zCode                          #import func to display the Python code
filename = os.path.abspath(__file__)  #get absolute file name 
zCode.display(filename)               #call it
#=================================================================================