Python Sorting is one of the very basic tasks that a new python user should have knowledge about. Alphabetically, Numbers, Tuples, and Objects are important fundamentals that are required for users to have knowledge about.
Python Sort list of Dictionaries by key
Sorting data is necessary to lessen its complexity and speed up and improve the effectiveness of searches. Because of this, sorting is crucial when working with a lot of data. Here, we’ll take the following course of action:
- • First, use the key value.iterkeys() function to alphabetically order the keys.
- • Next, use the sorted (key value) function to order the keys alphabetically and print the value for each key.
- • Third, use “key value.iteritems(), key = lambda (k, v): (v, k)”) to utilise key value to sort the values.
Example 1: Sorting the keys before displaying them
# the creation of a sorted dictionary
def dic():
k_val = {}
# Initializing value
k_val[1] = 7
k_val[4] = 6
k_val[6] = 34
k_val[3] = 90
k_val[2] = 12
k_val[5] = 87
print(“key_val”, k_val)
# An iterator across the dictionary’s keys is returned by iterkeys().
for j in sorted(k_val.keys()):
print(j, end=” “)
def main():
# function calling
dic()
# Main function calling
if __name__ == “__main__”:
main()
if __name__ == “__main__”: main()
The output will be:
key_val {1 : 7, 4 : 6, 6: 34, 3 : 90, 2:, 12, 5: 87}
>
1 2 3 4 5 6 >
Example 2: Arrange the dictionary according to the key and builds a sorted dictionary.
from collections import OrderedDict
dictionary = {‘aiman’: ‘1’, ‘andleab’: ‘9’,
‘uroosa’: ‘5’, ‘hassam’: ’20’, ‘khan’: ’23’}
d1 = OrderedDict(sorted(dictionary.items()))
print(d1)
Since the key’s type is a string in this example, we shall sort in lexicographical order.
The output will be:
Example 3: Using the Key to Sort the Values and Keys an in Alphabetical Order
In this Python example, we’re attempting to arrange the dictionary according to keys and values. To order the keys in this case, an iterator is used over the values of the Dictionary.
def dic():
k_val = {}
# Initialize value
k_val[1] = 56
k_val[3] = 2
k_val[6] = 12
k_val[2] = 24
k_val[4] = 18
k_val[5] = 323
print(“key_value”,k_val)
for k in sorted(k_val):
print((k, k_val[k]), end=” “)
def main():
dic()
if name == “main”:
main()
The output will be:
Python Sort list by Length
This Python program sorts a list by the length of its items. A list is given to the program, which then sorts it by element length.
Also Read: Best Way to Fix “nameerror: name nltk is not defined” in Python
Dispute Resolution
- Count the first list’s elements and put the total number of items into a variable.
- Consider each item on the list one at a time.
- Next, sort the list using the element length as the key.
- Show the ordered list.
- Exit.
Here is the Python program’s source code for sorting a list by the length of its elements. Also given below is the output of the application.
b=[]
m=int(input(“Enter total number of entries:”))
for k in range(1,m+1):
c=input(“Enter Numbers:”)
b.append(c)
b.sort(key=len)
print(b)
The output will be:
Enter total number of entries : 4
Enter Numbers: 34
Enter Numvers: 43
Enter Numbers : 67
Enter Numbers: 9
[‘9′, ’34’, ’43’, ’67’]
- The user must input and save in a variable how many elements the first list will have.
- The user must then use a for loop to manually enter each element of the list one at a time and save it in a list.
- After that, the items’ lengths are used as the determining factor in sorting the list.
- After that, the organized list is printed.
Python Sort list by Second Element
Two approaches to doing this will be shown. Two methods can be used such as by using bubble sort and second method employ sort() method.
Using Bubble Sort
To do the sorting, we used the Bubble Sort method. We have attempted to use nested loops to get the second member of the sublists. This uses the in-place sorting technique. Like the Bubble Sort, the temporal complexity is O(n2).
def Sort(s_li):
l = len(s_li)
for i in range(0, l):
for j in range(0, l-i-1):
if (s_li[j][1] > s_li[j + 1][1]):
tempo = s_li[j]
s_li[j]= s_li[j + 1]
s_li[j + 1]= tempo
return s_li
s_li =[[‘aiman’, 10], [‘mubashir’, 5], [‘ehtsham’, 20], [‘qudsia’, 15]]
print(Sort(s_li))
Output will be shown as:
[ [‘mubashir’, 5], [‘aiman’, 10], [‘qudsia’, 15], [‘ehtsham’, 20]]
Using the sort() method to order things
The tuple’s real contents are modified while sorting using this approach, but the in-place method of sorting is still used.
def Sort(s_li):
s_li.sort(key = lambda x: x[1])
return s_li
s_li =[[‘aiman’, 10], [‘mubashir’, 5], [‘romaisa’, 20], [‘ramez’, 15]]
print(Sort(s_li))
The output will be:
[[‘mubashir’, 5], [‘aiman’, 10], [‘ramez’, 15], [‘romaisa’, 20]]
Python List sort() Method with Examples
Using the ascending or descending order, the sort() method arranges the elements in a list.
Sorting list in Ascending order
odd = [11, 5, 7, 9, 3]
# arranging in ascending order
odd.sort()
print(odd)
The output will be:
[3, 5, 7, 9, 11]
List Sorting in Descending Order
#descending order
odd = [1, 3, 5, 11, 57]
odd.sort(reverse=True)
# print odd numbers print(‘Sorted list (in Descending):’, odd)
The output will be:
Sorted list (in Descending): [57, 11, 5, 3, 1]
Python Sort List of Tuples by First Element
To arrange a list of tuples by the first entry in Python, use the sorted() function or in place sort. The key term must be used in both approaches. The initial list of tuples won’t change as a result of this method.
Let us explain it with an example.
a = [(3, 8), (0, 9), (1, 7)]
#sorting by first element in record
srt = sorted(a, key=lambda tup: tup[0])
print(srt)
The output will be:
[(0, 9), (1, 7), (3, 8)]
FAQs
Python uses what sorting algorithm?
The various sorting methods that Python implements include Bubble Sort. and Sort by selection.
What are tuple list sorting techniques?
So, sorting a list is as simple as using the sort() method. We will first use an unordered list of tuples before invoking the sort() method. When we supply the input reverse=True to the sort() method, the order will change from rising (ascending) to decreasing (descending)