In [1]:
#Sorting a List of Integers
ages = [34, 23, 45, 32, 40, 29]
sorted_ages = sorted(ages)
print("Sorted ages:", sorted_ages)
sorted_ages_desc = sorted(ages, reverse=True)
print("Sorted ages (desc):", sorted_ages_desc)
Sorted ages: [23, 29, 32, 34, 40, 45] Sorted ages (desc): [45, 40, 34, 32, 29, 23]
In [2]:
#Sorting a List of Strings
names = ["Alice", "Bob", "Charlie", "David"]
sorted_names = sorted(names)
print("Sorted names:", sorted_names)
sorted_names_desc = sorted(names, reverse=True)
print("Sorted names (desc):", sorted_names_desc)
Sorted names: [''''Alice'''', ''''Bob'''', ''''Charlie'''', ''''David''''] Sorted names (desc): [''''David'''', ''''Charlie'''', ''''Bob'''', ''''Alice'''']
In [3]:
import pprint
#Sorting a List of Dictionaries
patients = [
{"name": "Alice", "age": 34, "condition": "Diabetes"},
{"name": "Bob", "age": 23, "condition": "Hypertension"},
{"name": "Charlie", "age": 45, "condition": "Asthma"},
{"name": "David", "age": 32, "condition": "Diabetes"}
]
sorted_by_age = sorted(patients, key=lambda x: x["age"])
print("Sorted by age:")
pprint.pp(sorted_by_age)
sorted_by_name = sorted(patients, key=lambda x: x["name"])
print("Sorted by name:")
pprint.pp(sorted_by_name)
Sorted by age: [{''''name'''': ''''Bob'''', ''''age'''': 23, ''''condition'''': ''''Hypertension''''}, {''''name'''': ''''David'''', ''''age'''': 32, ''''condition'''': ''''Diabetes''''}, {''''name'''': ''''Alice'''', ''''age'''': 34, ''''condition'''': ''''Diabetes''''}, {''''name'''': ''''Charlie'''', ''''age'''': 45, ''''condition'''': ''''Asthma''''}] Sorted by name: [{''''name'''': ''''Alice'''', ''''age'''': 34, ''''condition'''': ''''Diabetes''''}, {''''name'''': ''''Bob'''', ''''age'''': 23, ''''condition'''': ''''Hypertension''''}, {''''name'''': ''''Charlie'''', ''''age'''': 45, ''''condition'''': ''''Asthma''''}, {''''name'''': ''''David'''', ''''age'''': 32, ''''condition'''': ''''Diabetes''''}]