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)


No comments:

Post a Comment

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

Anu