0

working with dictionaries and functions in python

Task

Create a program that initiates a sequence list of dictionaries as below:

NameAgeLength
Tom1980
John2090
Jony1791
Mick1588
Donal1689
David2185

This program has three functions in process module and these modules are:

  • sorting_by_name, this will return a sorted list dictionary based on the name
  • sorting_by_length, this will return a sorted list dictionary based on the length

sorting_by_age, this will return a sorted list dictionary based on the age

Code

from datetime import date

today = date.today().strftime("%b %d, %Y")
stu_data = [{"Name": "Tom","Age":19,"Length":80},
{"Name": "John","Age":20,"Length":90},
{"Name": "Jony","Age":17,"Length":91},
{"Name": "Mick","Age":15,"Length":88},
{"Name": "Donal","Age":16,"Length":89},
{"Name": "David","Age":21,"Length":85}
]

def sorting_by_name(list):
return sorted(list, key = lambda i: i['Name'])

def sorting_by_length(list):
return sorted(list, key = lambda i: i['Length'])

def sorting_by_age(list):
return sorted(list, key = lambda i: i['Age'])


print("Original Dictionary: ",stu_data)
print("Sorted_by_name: ",sorting_by_name(stu_data))
print("Sorted_by_length: ",sorting_by_length(stu_data))
print("Sorted_by_age: ",sorting_by_age(stu_data))

Output

Original Dictionary:  [{'Name': 'Tom', 'Age': 19, 'Length': 80},
{'Name': 'John', 'Age': 20, 'Length': 90},
{'Name': 'Jony', 'Age': 17, 'Length': 91},
{'Name': 'Mick', 'Age': 15, 'Length': 88},
{'Name': 'Donal', 'Age': 16, 'Length': 89},
{'Name': 'David', 'Age': 21, 'Length': 85}]
Sorted_by_name: [{'Name': 'David', 'Age': 21, 'Length': 85},
{'Name': 'Donal', 'Age': 16, 'Length': 89},
{'Name': 'John', 'Age': 20, 'Length': 90},
{'Name': 'Jony', 'Age': 17, 'Length': 91},
{'Name': 'Mick', 'Age': 15, 'Length': 88},
{'Name': 'Tom', 'Age': 19, 'Length': 80}]
Sorted_by_length: [{'Name': 'Tom', 'Age': 19, 'Length': 80},
{'Name': 'David', 'Age': 21, 'Length': 85},
{'Name': 'Mick', 'Age': 15, 'Length': 88},
{'Name': 'Donal', 'Age': 16, 'Length': 89},
{'Name': 'John', 'Age': 20, 'Length': 90},
{'Name': 'Jony', 'Age': 17, 'Length': 91}]
Sorted_by_age: [{'Name': 'Mick', 'Age': 15, 'Length': 88},
{'Name': 'Donal', 'Age': 16, 'Length': 89},
{'Name': 'Jony', 'Age': 17, 'Length': 91},
{'Name': 'Tom', 'Age': 19, 'Length': 80},
{'Name': 'John', 'Age': 20, 'Length': 90},
{'Name': 'David', 'Age': 21, 'Length': 85}]

keep visiting : shaadcoding

shaad

Leave a Reply

Your email address will not be published. Required fields are marked *