0% found this document useful (0 votes)
5 views3 pages

Python Sorting Techniques Explained

The document demonstrates various ways to sort lists, tuples, strings, sets, and dictionaries in Python. It shows how to use the built-in sort() and sorted() functions to sort the elements in different data structures in both ascending and descending order. It also provides examples of custom sorting by passing a key function to sorted() to sort based on a specific element, attribute, or property rather than the default natural sorting order.

Uploaded by

Mouparna Sen
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views3 pages

Python Sorting Techniques Explained

The document demonstrates various ways to sort lists, tuples, strings, sets, and dictionaries in Python. It shows how to use the built-in sort() and sorted() functions to sort the elements in different data structures in both ascending and descending order. It also provides examples of custom sorting by passing a key function to sorted() to sort based on a specific element, attribute, or property rather than the default natural sorting order.

Uploaded by

Mouparna Sen
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

names = ["apple", "google", "yahoo", "amazon", "facebook", "instagram"]

[Link]()
print(names)

print(sorted(names)) # returns a newly sorted list


print(names) # original list remains unchanged

[Link](reverse=True)
print(names)

print(sorted(names, reverse=True))

# sorting sets
s = {2, 1, 5, 3, 7, 4}
print(sorted(s))

###################################################################
# sorting immutable datatypes

# sorting strings
word = "helloworld"
sorted_word = sorted(word) # returns a list
print("".join(sorted_word))

# sorting tuples
t = (1, 2, 3, 5, 2, 9, 6, 0, 7, 4)
print(tuple(sorted(t))) # returns a list

#################################################################
# sorting a dictionary

prices = {"ACME": 45.23, "AAPL": 612.78, "IBM": 205.55, "HPQ": 37.20,


"FB":10.75}

# sorting only keys


print(sorted(prices))
print(sorted([Link]()))

# sorting only values


print(sorted([Link]()))

#################################################################
# custom sorting

# sorting a list based on its element's length


names = ["apple","facebook", "google", "instagram", "yahoo", "amazon"]

# key accepts only functions


print(sorted(names, key=len))

#sorting a list based on last character of each item


items = ["bv", "aw", "dt", "cu"]
print(sorted(items, key=lambda x: x[-1]))

#sorting based on city names


temperatures = [("Chennai", 37), ("bangalore", 25), ("Mumbai", 32), ("delhi",
35)]
print(sorted(temperatures))
print(sorted(temperatures, key=lambda x: x[0]))
# sorting based on temperatures
print(sorted(temperatures, key=lambda item: item[-1]))

# sort dictionary based on values


prices = {"ACME": 45.23, "AAPL": 612.78, "IBM": 205.55, "HPQ": 37.20,
"FB":10.75}

s_prices = sorted([Link](), key=lambda item: item[-1])


print(s_prices)
print(sorted([Link]()))

# getting minimum and maximum values


min_, *_, max_ = s_prices
print(min_)
print(max_)

# or

min_price = min(s_prices, key=lambda item: item[-1])


max_price = max(s_prices, key=lambda item: item[-1])

##############################################################
portfolio = [
{"name": "IBM", "shares": 100, "price": 91.1},
{"name": "AAPL", "shares": 50, "price": 543.22},
{"name": "FB", "shares": 200, "price": 21.09},
{"name": "HPQ", "shares": 35, "price": 31.75},
{"name": "YHOO", "shares": 45, "price": 16.35},
{"name": "ACME", "shares": 73, "price": 115.65},
]

print(sorted(portfolio, key=lambda item: item["name"]))


print(sorted(portfolio, key=lambda item: item["price"]))

###############################################################################
data = [
{"fname": "Steve", "eid": 1003, "lname": "Wazniak"},
{"fname": "Steve", "eid": 1002, "lname": "Jobs"},
{"fname": "Alex", "eid": 1001, "lname": "Martin"},
{"fname": "Brain", "eid": 1004, "lname": "Jones"},
]

"""
item = [("steve", "wazniak")]
item = ("steve", "jobs)
"""

def get_name(item):
return item["fname"], item["lname"]

print(sorted(data, key=get_name))

print(sorted(data, key=lambda item: (item["fname"], item["lname"])))


"""
1. [Link]() , sorted(list)
2. sorted(tuple)
3. sorted(string)
4. sorted(set)
5. sorting a dictionary
1. keys : sorted(dict), sorted([Link]()), sorted([Link](),
key=lambda x: x[0]))
2. values: sorted([Link]()), sorted([Link](), key=lambda x:x[-1])

"""

NOTE : Sorted() returns a list irrespective of the iterable we have passed

You might also like