Dictionary methods

 # Dictionary Manipulation 


"""

Create a dictionary containing employee name and id (name:id). 

Display

1. Employee names, sorted in alphabetical order

2. Employee name and id, sorted alphabetically by name

3. Inverse the dictionary (id : name)

"""


# Program


# Creating dictionary

Emp_ID = {'Alice':283, 'Larry':185, 'Cathy':307, 'Gary':585, 'Dan':427, 'Bob':734, 'Ed':564, 'Helen':370, 'Jack':609, 'Irene':921, 'Frank':478, 'Kelly':154}


print(Emp_ID)


# 1. Employee names, sorted in alphabetical order

print("Employee names - sorted alphabetically")

Emp_Names = sorted(Emp_ID.keys())

print("\n".join(Emp_Names))


# 2. Employee name and id, sorted alphabetically by name

print("Employee name and id - sorted alphabetically")

SD = {k:Emp_ID[k] for k in sorted(Emp_ID.keys())}

for k in SD:

print(k.ljust(10), SD[k])

# 3. Inverse the dictionary (id : name)

print("Inverse Dictionary")

InvD = {v:k for k,v in Emp_ID.items()}

for k in InvD:

print(k,"\t",InvD[k])


No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu