Showing posts with label dictionary methods. Show all posts
Showing posts with label dictionary methods. Show all posts

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])


Dictionary manipulation - sorting

 # Dictionary Manipulation


"""

Consider two lists

NAMES = ['Alice', 'Larry', 'Cathy', 'Gary', 'Dan', 'Bob','Ed', 'Helen', 'Jack', 'Irene', 'Frank', 'Kelly']

AGES = [20, 21, 18, 18, 19, 20, 20, 19, 19, 19, 22, 19]

These lists match up, so Alice’s age is 20, Larry’s age is 21, and so on. Write a program that 

1. Combines these lists into a dictionary.

2. Reads a name and returns the age.

3. Reads an age and returns the names of all the people who are that age.

4. Sort dictionary by name.

5. Sort dictionary by age.

"""


# Program


import operator


# Given List

NAMES = ['Alice', 'Larry', 'Cathy', 'Gary', 'Dan', 'Bob','Ed', 'Helen', 'Jack', 'Irene', 'Frank', 'Kelly']

AGES = [20, 21, 18, 18, 19, 20, 20, 19, 19, 19, 22, 19]


# 1. Combines these lists into a dictionary.


D = { k:v for k,v in zip(NAMES,AGES)}

print(D)


# 2. Reads a name and returns the age.


Name = input("Enter name : ")

if Name in D:

print("Name :",Name)

print("Age :",D[Name])

else:

print("No data for",Name)

# 3. Reads an age and returns the names of all the people who are that age.


Age = int(input("Enter age : "))

Keys = [k for k,v in D.items() if v==Age]


if (len(Keys)==0):

print("No match for given age")

else:

print("People in same age:")

for k in Keys:

print(k)


# 4. Sort dictionary by name.


SD_Keys = {k:D[k] for k in sorted(D)}

print(SD_Keys)


# 5. Sort dictionary by age.

# Sorts by value and for same values sorts keys lexicographically 


SD_val = {v[0] : v[1] for v in sorted(D.items(), key = lambda x: (x[1], x[0]))}

print(SD_val)