Python Programming - Sorting Key And Value

You can learn about Dictionaries in Python Programs with Outputs helped you to understand the language better.

Python Programming – Sorting Key And Value

Creating the dictionary with a set of key: value pairs can be accomplished if all the data items are known in advance. Dictionaries do not have an inherent order. To impose order while processing a dictionary, you have to sort it using the sorted ( ) function. Looping over the sorted list of keys using sorted(ls), the dictionary content is printed out with the keys in alphabetical order as given below:

Is = {‘Uma’:76, ‘Mohan’:85, ‘Beena’:92, ‘Lisa’:28}
for s in sorted(Is): # s iterates over the sorted list of keys
print(s, ‘is’, Is [s], ‘years old.’)
>>>
Beena is 92 years old.
Lisa is 28 years old.
Mohan is 85 years old.
Uma is 76 years old.
>>>

But what if you want to sort by member’s age here, the key= option, i.e., key=ls.get to be exact. For the dictionary value can be achieved by specifying example,

for s in sorted(ls, key=ls.get):         # value-based sorting
print(s, ‘is’. Is [s], ‘years old. ‘ )
>>>
Lisa is 28 years old.
Uma is 76 years old.
Mohan is 85 years old.
Beena is 92 years old.
>>>

Example
Program to enter and display information in a dictionary.

# Program using dictionary to enter and display information on the screen rec=dict ( )
num=int(input(“Enter number of students :”))i=1
while i<=num:
name=input(“Enter name of student :”)
per=input (“Enter marks% of student :”)
rec[name]=per
i = i+1
print(“Name of Student”,”\t”,”marks%”)
for i in rec:
print(“\t”,i,”\t\t”,rec[i])RUN
>>>
Enter the number of students :3
Enter the name of student : Gagan
Enter marks% of student:87%
Enter the name of student: Geeta
Enter marks% of student:69%
Enter the name of the student: Anita
Enter marks% of student:95%
Name of Student %marks
Gagan 87%
Geeta 69%
Anita 95%
>>>

Example
Program to enter name and percentage of marks in a dictionary, and then dis¬play information according to marks percentage, i.e., value-based.

# Program using dictionary to enter and display information in sorted order according to marks%
rec=dict ( )
num=int(input(“Enter number of students ))
i=1
while i<=num:
name=input(“Enter name of student :”)
per=int(input (“Enter marks% of student :”))
rec[name]=per
i = i + 1
Is = rec.keys ( )
print (“Name of Student”,”\t”,”marks%”)
for i in sorted(Is,key=rec.get) :
print (“\t” , i, “\t\t” , rec[i] )RUN
>>>
Enter Number of students:4
Enter name of student :Uma
Enter marks% of student :56
Enter name of student :Tina
Enter marks% of student :84
Enter name of student :Sonu
Enter marks% of student :98
Enter name of student :Yash
Enter marks% of student :45
Name of Student marks%
Yash 45
Uma 5 6
Tina 84
Sonu 98
>>>

Dictionary Keys are case sensitive i.e., same key name but with the different case are treated as different keys in python dictionaries.

Leave a Reply

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